将ListBox与ValueMember绑定
本文关键字:绑定 ValueMember ListBox | 更新日期: 2024-09-23 01:58:53
我扩展了ListBox来构建我的CustomListbox。
它将接受类对象数组作为数据源,我重写OnDrawItem(),通过读取类对象数组来显示它们。
到目前为止,一切都很顺利。问题是我无法读取列表框的ValueMember,因为我没有分配它。我想将我的classObject的一个属性添加为Value Member
伪代码:
public class myModel
{
int id;
string name;
XXXXXXXXX
XXXXXXXXX
}
myModel[] ds = getData();
//myCustomListbox.ValueMember = "id"; //this doesnt seem to work
myCustomListbox.DataSource =ds;
我重复一遍,OnDrawItem()将绘制所需的显示值。有没有什么方法可以像这样重写来添加值项?
绑定仅适用于属性。将字段更改为属性(并确保它是公共的-默认情况下类成员是私有的)
public class myModel
{
public int id { get; set; }
public string name { get; set; }
// ...
}
现在一切都应该好了:
myModel[] ds = getData();
myCustomListbox.ValueMember = "id";
myCustomListbox.DataSource = ds;
BTW C#命名指南建议对属性、方法和类型名称使用Pascal Names。
ListBox与C#中的数据表绑定(在windows应用程序中)是添加值成员所必需的
如果我们使没有值成员的代码如下所示,
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
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...
}
输出将是…
表中特定列的列表。此处为"数据"。