How to get selected data from combobox and upload it to mysql database?
I want to get selected data from combobox and upload it to mysql database, but it's not working as expected. Here is my code:
Try Dim cmd2 As New MySqlCommand Dim insertStatment As String = "INSERT INTO comment (name,comment,reason) VALUES (@name,@comment, @reason)" cmd2 = New MySqlCommand(insertStatment, db_con) cmd2.Parameters.AddWithValue("@name", txtname.Text) cmd2.Parameters.AddWithValue("@comment", richtxtcomment.Text) cmd2.Parameters.AddWithValue("reason", combobox.SelectedValue) cmd2.ExecuteNonQuery() MessageBox.Show("Thank your for your comment") Catch ex As Exception MessageBox.Show("bad") db_con.Close() Exit Sub End Try
Depending on how the items in your ComboBox were added, there are different properties to use:
- SelectedIndex gets the index of the selected item.
- SelectedItem gets the object that's selected.
- SelectedText gets the text that's selected.
- SelectedValue gets the ValueMember property of the selected item.
So if you didn't set the ValueMember property, then it's going to be null. If you want to store what's displayed in the combo box, use SelectedText:
If you want to store some property or the result of a method of the object in the ComboBox use SelectedItem: