2013-12-14 78 views
0

我擴展了ListBox以構建我的CustomListbox。用ValueMember綁定列表框

它將接受classobject數組作爲數據源,我重寫OnDrawItem()以通過讀取classobject數組來顯示它們。

高興在這裏一切工作正常。問題是我無法讀取Listbox的ValueMember,因爲我沒有分配它。我想補充的超值會員

僞碼我classObject的特性之一:

public class myModel 
{ 
    int id; 
    string name; 
    XXXXXXXXX 
    XXXXXXXXX 
} 

myModel[] ds = getData(); 
//myCustomListbox.ValueMember = "id"; //this doesnt seem to work 
myCustomListbox.DataSource =ds; 

我重複一次,的OnDrawItem()將繪製所需的顯示值。有沒有什麼方法可以像這樣重寫來添加Value Items呢?

回答

0

綁定僅適用於屬性。你的字段更改爲財產(並確保它是公共的 - 默認類成員是私有的)

public class myModel 
{ 
    public int id { get; set; } 
    public string name { get; set; } 
    // ... 
} 

現在都應該是OK:

myModel[] ds = getData(); 
myCustomListbox.ValueMember = "id"; 
myCustomListbox.DataSource = ds; 

BTW C#naming guidelines建議使用帕斯卡爾名稱的屬性,方法和類型名稱。

+0

是的,有getter和setter,但仍然不工作。 – Robert

+0

@Rams是你的財產被標記爲公共?你也可以展示你如何閱讀價值成員? –

+0

是的,他們都是公開的,並且a的值總是空的(在點擊項目之後)在SelectedIndexChanged事件中的字符串a = myCustomListBox.ValueMember – Robert

0

ListBox與C#中的數據表綁定(在Windows應用程序中)是添加值成員所必需的。

如果我們作出以下

System.Data.DataRowView

對於上述代碼的輸出給出,而不象如下值構件的代碼,

private void button1_Click(object sender, EventArgs e) 
    { 
     SqlDataAdapter da = new SqlDataAdapter("select * from Table1",con); 
     da.Fill(dt); 

     listBox1.DataSource = dt; 
     // listBox1.ValueMember = "data"; //data is one of the coloumn of the table... 

    } 

System.Data.DataRowView

System.Data.DataRowView

如果我們提供值構件在這樣的代碼如下

private void button1_Click(object sender, EventArgs e) 
    { 
    SqlDataAdapter da = new SqlDataAdapter("select * from Table1",con); 
    da.Fill(dt); 
    listBox1.DataSource = dt; 
    listBox1.ValueMember = "data"; //data is one of the coloumn of the table... 
    } 

的輸出將是...

的特定列的列表在桌子裏。這裏'數據'。