'Failed to convert parameter value from a String to a Int32/

后端 未结 1 892
心在旅途
心在旅途 2021-01-26 04:00

I have already post this question but now in details. I have trying to insert Date from Vb.net to SQL Database But when i click insert Button then show me above error message.I

1条回答
  •  野的像风
    2021-01-26 04:24

    Give this a go:

    Dim r as New Regex("[^0-9]")
    
    cmd.Parameters.Add("@EmpID", SqlDbType.Int).Value = r.Replace(EmpID.Text, "")
    cmd.Parameters.Add("@EmpSalary", SqlDbType.Int).Value = r.Replace(EmpSalary.Text, "")
    cmd.Parameters.Add("@EmpName", SqlDbType.VarChar).Value = EmpName.Text
    cmd.Parameters.Add("@FatherName", SqlDbType.VarChar).Value = FatherName.Text
    cmd.Parameters.Add("@EmailAddress", SqlDbType.VarChar).Value = EmailAddress.Text
    cmd.Parameters.Add("@BankAccount", SqlDbType.Int).Value = r.Replace(BankAccount.Text, "")
    cmd.Parameters.Add("@HomeAddress", SqlDbType.VarChar).Value = HomeAddress.Text
    cmd.Parameters.Add("@PersonalMobile", SqlDbType.Int).Value = r.Replace(PersonalMobile.Text, "")
    cmd.Parameters.Add("@DtpDOB", SqlDbType.Date).Value = DtpDOB.Value
    cmd.Parameters.Add("@img", SqlDbType.Image).Value = img
    

    It strips out non numbers present in text fields, meaning the conversion should succeed..

    It would, however be better to a) Use a MaskedTextBox, a NumericUpDown or a textbox that rejects non-numbers and b) convert the text to int yourself so you can handle if it fails, using a nice error message:

    Try
        cmd.Parameters.Add("@EmpID", SqlDbType.Int).Value = Convert.ToInt32(EmpID.Text)
        cmd.Parameters.Add("@EmpSalary", SqlDbType.Int).Value = Convert.ToInt32(EmpSalary.Text)
        ...
    Catch ex as Exception
        'the last added parameter is the one that hit the problem
        MessageBox.Show($"Error adding a value for {cmd.Parameters.Last().ParameterName}")
    End Try
    

    0 讨论(0)
提交回复
热议问题