Pantheo Pantheo -4 years ago 131
Vb.net Question

Insert the values of a combo box into an SQL Server DB table Visual Basic 2010 (Visual Studio 2010)

Good evening.
I want to insert data to a table in SQL DB.I have a combo box with the values "5" and "6". When you click one or the other in the combo box i want these values to be inserted in a database( MS SQL Server 2008).I also have some textboxes which are bind correnctly and have no problem. The problem is with the bindings(i guess) of the combo box. I get sql exception.

Here is a snippet. Any help would be appreciated.Thanks

Private Sub BindFields()
txtSurname.DataBindings.Add("Text", ObjDataView, "surname")
txtName.DataBindings.Add("Text", ObjDataView, "name")
cboColor.DataBindings.Add(cboColor.SelectedValue.ToString, ObjDataView, "color")
End Sub

Private Sub Customers_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cboColor.Items.Add("5")
cboColor.Items.Add("6")

FillDataSetAndView()
BindFields()
End Sub


Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click

Dim objCommand As SqlCommand = New SqlCommand()
Dim intPosition As Integer
intPosition = objCurrencyManager.Position

ObjConnection.Open()
objCommand.Connection = ObjConnection
objCommand.CommandText = "INSERT INTO tblCustomers" & "(name, surname, color)" & "VALUES(@name,@surname,@color);"
objCommand.Parameters.AddWithValue("@name", txtName.Text)
objCommand.Parameters.AddWithValue("@surname", txtSurname.Text)
objCommand.Parameters.AddWithValue("@color", cboColor.SelectedValue.ToString)
Try
objCommand.ExecuteNonQuery()
Catch SqlExceptionErr As SqlException
MessageBox.Show(SqlExceptionErr.Message)
End Try

ObjConnection.Close()


FillDataSetAndView()
BindFields()


objCurrencyManager.Position = intPosition
ShowPosition()
End Sub

Answer Source

Inspect the cboColor.SelectedValue; it is not initialized and set to nothing. Attempting to call ToString on .SelectedValue will generate a Null Reference exception. I believe what you want is the cboColor.Text property; this will pull whatever the current text of whatever value the combobox is currently displaying.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download