When i get SelectedItem in combobox return System.Data.DataRowView

后端 未结 5 639
暖寄归人
暖寄归人 2020-12-21 14:26

this is a function for retrive two field in sql to combobox : Code :

public void FillCmbKala()
    {
        cmbKala.Items.Clear();
                 


        
相关标签:
5条回答
  • 2020-12-21 14:39

    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;
    }
    
    0 讨论(0)
  • 2020-12-21 14:44

    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)";  
    
    0 讨论(0)
  • 2020-12-21 14:45

    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];
    
     }
    

    try using Use the code where you want to access the values........

    string dept = cmb_dept.Text; MessageBox.Show("val=" + dept);
    YOUR combobox.text = System.Data.DataRowView Will be Solved ##
    
    0 讨论(0)
  • 2020-12-21 14:55

    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?

    0 讨论(0)
  • 2020-12-21 14:57
     DataRowView dv = (DataRowView)comboBox1.SelectedItem;
            string s = (string)dv.Row["kName"];
            int m1 = (int)dv.Row["kID"];
    
    0 讨论(0)
提交回复
热议问题