JanOlMajti
JanOlMajti

Reputation: 1397

System.Data.DataRowView, c#

I've got a problem:

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

It returned System.Data.DataRowView in every row.

I tried:

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

and I get error:

Cannot bind to the new display member. Parameter name: newDisplayMember

I want to get idUser and name. Thanks

Upvotes: 2

Views: 3450

Answers (2)

Alok
Alok

Reputation: 274

Please use below

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

Upvotes: 4

Kev Ritchie
Kev Ritchie

Reputation: 1647

You need to return the ID in your SELECT statement and assign the DataTable as the DataSource after you have filled the DataTable:

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

You can then set up the ComboBox as such:

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

UPDATE

If you want to access the selected text or value of the item selected in the ComboBox, then you will need to do something like:

DataRowView drvItem = comboBox1.SelectedItem as DataRowView;

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

Upvotes: 4

Related Questions