简体   繁体   中英

How can I access all values from a specific column in tables using linq and Entity Framework?

Can someone help me? I want to display all values from a specific column in a combo box using linq. I try to do it but I can't figure it out. I am new to linq and can't find a way to do it

If you want to show a list of string product names and be able to retrieve their int id you can for example:

combo.DisplayMember = "DisplayColumnName";
combo.ValueMember = "IdColumnName";
combo.DataSource = context.TableName.Select(r => 
  new KeyValuePair<int, string>(r.IdColumnName, r.DisplayColumnName)).ToList();

You need to replace TableName, DisplayColumnName and IdColumnName with your actual values.

To get the ID of what the user selected (eg for further db queries) you can:

var id = (int)combo.SelectedValue;

If you want the string of what the user selected:

var s = ((KeyValuePair)combo.SelectedItem).Value;

this works.

       var context = new LoginTest();
        var login = context.SignUps
             .Select(c => new { c.id, c.Name });
        comboBox1.DataSource = login.ToList();
        comboBox1.ValueMember = "id";
        comboBox1.DisplayMember = "Name";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM