当我在组合框中获取SelectedItem时返回System.Data.DataRowView

时间:2014-05-26 07:43:23

标签: c# combobox

这是sql到combobox中的retrive两个字段的函数: 代码:

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

当我使用组合框返回System.Data.DataRowView!

例如:

string str= cmbKala.SelectedItem;

结果是: str = System.Data.DataRowView

6 个答案:

答案 0 :(得分:5)

这是MSDN Reference

由于SelectedItem返回Object。它返回选中的特定行对象。以下是您获得价值的方式:

DataRowView oDataRowView = cmbKala.SelectedItem as DataRowView;
string sValue = string.Empty;

if (oDataRowView != null) {
   sValue = oDataRowView.Row["kName"] as string;
}

答案 1 :(得分:5)

 DataRowView dv = (DataRowView)comboBox1.SelectedItem;
        string s = (string)dv.Row["kName"];
        int m1 = (int)dv.Row["kID"];

答案 2 :(得分:0)

您选择的是DataRowView。您应该选择项目的ID或文本吗?像string str = cmbKala.SelectedItem.Text或string str = cmbKala.SelectedItem.Value?

答案 3 :(得分:0)

我知道这个问题已经过时了,但我只是想让你们知道,如果你收到这个错误,请确保你使用

    ComboBoxName.DisplayMemberPath = "name of the column that you want to show in the combobox (ex: name)"  
    ComboBoxName.SelectedValuePath = "name of the column (ex:id)";  

答案 4 :(得分:0)

这将非常有助于您

关于你想要编写此代码的加载事件

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

答案 5 :(得分:0)

这适用于 C# WPF:

Textbox.Text = (listbox.SelectedItem as DataRowView).Row["Purpose"] as string;