System.Data.DataRowView,c#

时间:2012-01-09 10:00:30

标签: c# visual-studio

我遇到了问题:

SqlDataAdapter da = new SqlDataAdapter("SELECT dbo.User.name FROM dbo.User", con);
DataTable dt = new DataTable();
comboBox1.DataSource = dt;
da.Fill(dt);

它在每一行都返回System.Data.DataRowView

我试过了:

comboBox1.ValueMember = "idUser";
comboBox1.DisplayMember = "dbo.User.name"

我收到错误:

  

无法绑定到新的显示成员。参数名称:   newDisplayMember

我想获得idUsername。 感谢

2 个答案:

答案 0 :(得分:4)

您需要在SELECT语句中返回ID,并在填充DataTable后将DataTable指定为DataSource:

 SqlDataAdapter da = new SqlDataAdapter("SELECT IDUser, Name FROM dbo.User", con);
 DataTable dt = new DataTable();
 da.Fill(dt); 

然后您可以设置ComboBox:

comboBox1.DataSource = dt.DefaultView;
comboBox1.ValueMember = "IDUser";
comboBox1.DisplayMember = "Name"

<强>更新

如果要访问ComboBox中所选项目的选定文本或值,则需要执行以下操作:

DataRowView drvItem = comboBox1.SelectedItem as DataRowView;

if (drvItem != null)
{
    label4.Text = drvItem["ID"].ToString();
    label3.Text = drvItem["Name"].ToString();
}

答案 1 :(得分:4)

请使用以下

SqlDataAdapter da = new SqlDataAdapter("SELECT IDUser, Name FROM dbo.User", con); 
DataTable dt = new DataTable();  
da.Fill(dt);  
comboBox1.DataSource = dt; 
comboBox1.ValueMember = "IDUser";   
comboBox1.DisplayMember = "Name";