Search code examples
c#combobox

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


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

public void FillCmbKala()
    {
        cmbKala.Items.Clear();
        objCon.Connecting();
        string SQL = "SELECT [kID],[kName] FROM tblKala ORDER BY kName";
        DataSet ds = new DataSet();
        using (SqlConnection cn = new SqlConnection(objCon.StrCon))
        {
              using (SqlDataAdapter adapter = new SqlDataAdapter(SQL, cn))
              {

                  cn.Open();

              try
              {
                  adapter.Fill(ds);
              }
              catch (SqlException e)
              {

                  MessageBox.Show("There was an error accessing your data of 'Kala'. DETAIL: " + e.ToString());
              }
              finally
              {
                 cn.Close();
              }
          }
     }
     cmbKala.DataSource = ds.Tables[0];
     cmbKala.DisplayMember = "kName";
     cmbKala.ValueMember = "kID";
}

when i use the combobox return System.Data.DataRowView !

For Example :

string str= cmbKala.SelectedItem;

result is : str= System.Data.DataRowView


Solution

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