Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
842 views
in Technique[技术] by (71.8m points)

c# - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...