this is a function for retrive two field in sql to combobox : Code :
public void FillCmbKala()
{
cmbKala.Items.Clear();
Here is MSDN Reference.
As SelectedItem
returns Object. It returns specific row object which is selected. Here is how you will get value:
DataRowView oDataRowView = cmbKala.SelectedItem as DataRowView;
string sValue = string.Empty;
if (oDataRowView != null) {
sValue = oDataRowView.Row["kName"] as string;
}
I know that this question is old, but I just wanted to let you guys know that If you get this error make sure you are using
ComboBoxName.DisplayMemberPath = "name of the column that you want to show in the combobox (ex: name)"
ComboBoxName.SelectedValuePath = "name of the column (ex:id)";
THIS WILL DEFINITELY HELP TO YOU
on the load Event you want to Just Write this code
onformload()
{
cmb_dept.Items.Clear();
SqlConnection conn = new SqlConnection(@"DATA SOURCE=(localdb)\MSSQLLocalDB;INTEGRATED SECURITY=true;INITIAL CATALOG=EMPLOYEE;");
conn.Open();
SqlCommand command = new SqlCommand("select dept_id, dept_name from department", conn);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
cmb_dept.ValueMember = "dept_id";
cmb_dept.DisplayMember = "dept_name";
cmb_dept.DataSource = ds.Tables[0];
}
string dept = cmb_dept.Text; MessageBox.Show("val=" + dept);
YOUR combobox.text = System.Data.DataRowView Will be Solved ##
The thing you are selecting IS a DataRowView. You should select the id of the item or the text instead right? Like string str= cmbKala.SelectedItem.Text or string str= cmbKala.SelectedItem.Value?
DataRowView dv = (DataRowView)comboBox1.SelectedItem;
string s = (string)dv.Row["kName"];
int m1 = (int)dv.Row["kID"];