2012-03-30 54 views
0

當我在組合框中選擇僱員姓名,我需要在一個文本框我怎樣才能從LINQ查詢選定的項目在一個變量

using (LINQtoEntitiesEntities MyEntities = new LINQtoEntitiesEntities()) 
{ 
    ObjectQuery<Employee> Emp = MyEntities.Employee; 
    comboBox1.DataSource = (from u in Emp select new { u.ID, u.Name, u.BirthDate }).ToList(); 
    comboBox1.ValueMember = "ID"; 
    comboBox1.DisplayMember = "Name"; 
    TextBox1.Text = ....................... ; 
} 

我需要得到u.BirthDate在變量顯示員工出生日期從查詢 我該怎麼做?

回答

1

也許這樣?

TextBox1.Text = ((IEnumerable<Employee>)comboBox1.DataSource) 
    .Where(e => e.ID == comboBox1.Value) 
    .First().BirthDate; 
4

添加它馬上蝙蝠嘗試:

var employees = (from u in Emp select new { u.ID, u.Name, u.BirthDate }).ToList(); 
comboBox1.DataSource = employees; 

if(employees.Any()) 
    TextBox1.Text = employees.First(x => x.BirthDate); 

動態地改變它,當你改變了組合框,你可以在下面的事件處理程序添加到您的SelectionChangeCommitted事件:

private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e) 
{ 
    ComboBox senderComboBox = (ComboBox) sender; 

    var selectedObject = senderComboBox.SelectedItem; 

    if(selectedObject == null) return; 

    TextBox1.Text = ((IEnumerable<Employee>)senderComboBox.DataSource) 
         .First(emp => emp.ID == senderComboBox.Value).BirthDate; 

} 

(假定生日是一個字符串);

相關問題