我在数据表中有ProjectID和Name。 cbProjects是ComboBox。
这是一段代码。
ProjectEntities projectE = new ProjectEntities();
cbProjects.ItemsSource = projectE.Projects;
cbProjects.DisplayMemberPath = "Name";
我可以在ComboBox中获取有关所选名称的ProjectID的信息吗?
答案 0 :(得分:2)
private void cbProjects_SelectedIndexChanged(object sender, System.EventArgs e)
{
ComboBox cb = sender as ComboBox;
var item = cb.SelectedItem as Project;
int projectID = item.ProjectID;
}
或
var item = cbProjects.SelectedItem as Project;
int projectID = item.ProjectID;
答案 1 :(得分:2)
我正在使用VS 2010和EF 4,这是代码,它对我有用:
//load entities to the combo box
ProjectEntities projectE = new ProjectEntities();
var pdata = projectE.Projects;
cbProjects.DataSource = pdata; //cbProjects.ItemsSource
cbProjects.DisplayMember = "Name"; //cbProjects.DisplayMemberPath
//get selected value
var item = cbProjects.SelectedItem as Project;
int projectID = item.ProjectID;
答案 2 :(得分:1)
cbProjects.SelectedValuePath = "ProjectID"
然后,您可以通过cbProjects.SelectedValue
获取所选项目的ID。