2013-03-18 27 views
0

如何爲來自System.Data的DataRow綁定DisplayMemberPath和SelectedValuePath?如何爲來自System.Data的DataRow綁定設置DisplayMemberPath和SelectedValuePath?

這就是我在做的,是不是錯誤?

DataSet ds = new DataSet(); 
DataTable dt = new DataTable("tb1"); 
dt.Columns.Add("ID"); 
dt.Columns.Add("Name"); 
ds.Tables.Add(dt); 

DataRow dr1 = ds.Tables[0].NewRow(); 
dr1["ID"] = 1; 
dr1["Name"] = "Edwin"; 

DataRow dr2 = ds.Tables[0].NewRow(); 
dr2["ID"] = 2; 
dr2["Name"] = "John"; 

DataRow dr3 = ds.Tables[0].NewRow(); 
dr3["ID"] = 3; 
dr3["Name"] = "Dave"; 

ds.Tables[0].Rows.Add(dr1); 
ds.Tables[0].Rows.Add(dr2); 
ds.Tables[0].Rows.Add(dr3); 

comboBox1.DisplayMemberPath = "Name"; 
comboBox1.SelectedValuePath = "ID"; 

foreach (DataRow item in ds.Tables[0].Rows) 
{ 
    comboBox1.Items.Add(item); 
} 
+0

爲什麼不創建一個Class來保存這些信息,而不是用'System.Data'完成所有'magic string'的東西?用'string Name {get; set;}'和一個'int ID {get; set;}'屬性? – 2013-03-18 18:19:33

+0

你是否缺少ComboBox上的DataBind()..? – MethodMan 2013-03-18 18:20:51

回答

0

你加入DataRow對象的ComboBox,並DataRow沒有性質題爲IDName(以及技術上他們有一個Name屬性,但它不是你想的一個)

一個簡單的方法要記住是使用DisplayMemberPathSelectedValuePath,您需要能夠使用DataItem.PropertyName的語法訪問該屬性,所以在您的情況下它試圖訪問DataRow.IDDataRow.Name

例如,DisplayMemberPath只是一個快捷方式到一個數據模板,看起來像

<TextBlock Text="{Binding DisplayMemberPathValue}" /> 

你會更好,只是添加一些簡單的像一個KeyValuePair<int,string>或自定義類,甚至只是一個ComboBoxItem

comboBox1.SelectedValuePath = "Key"; 
comboBox1.DisplayMemberPath = "Value"; 

foreach (DataRow item in ds.Tables[0].Rows) 
{ 
    comboBox1.Items.Add(
     new KeyValuePair<int,string>((int)item["ID"], row["Name"] as string)); 
} 
+0

感謝您回答問題的時間,但我很好奇如何將數據列封裝在SelectedValuePath上。這似乎是合乎邏輯的,它不會是簡單的「ID」,但我也許可以通過更低級別的「row.column.ID」訪問,你知道我的意思嗎 – RollRoll 2013-03-19 01:58:47

相關問題