簡體   English   中英

如何設置System.Data中DataRow的綁定的DisplayMemberPath和SelectedValuePath?

[英]How to set DisplayMemberPath and SelectedValuePath for a binding from DataRow from System.Data?

如何設置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);
}

您正在將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));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM