你们中的一些人可能认为它已经在这个社区的其他地方得到了解决,但我无法真正解决它。
我有一个ComboBox,我喜欢用DataReader填充它。像往常一样,我创建了一个类来设置value member
和display member
。我的代码如下。
using (MySqlCommand cmd = new MySqlCommand("SELECT item_id, item_name FROM items WHERE status='active'", Class_Connection.conn))
{
MySqlDataReader rdr = cmd.ExecuteReader();
ArrayList temptbl = new ArrayList();
while (rdr.Read())
{
//MessageBox.Show(rdr.GetString(1).ToString() + "::" + rdr.GetString(0).ToString());
temptbl.Add(new Class_NameValue(rdr.GetString(1), rdr.GetString(0)));
}
rdr.Close();
// define Display and Value members
cmb_items.DisplayMember = "NameMember";
cmb_items.ValueMember = "IdMember";
// set the DataSource to the DataTable
cmb_items.DataSource = new BindingSource(temptbl, null);
}
Get-Set类如下:
class Class_NameValue
{
private string myNameMember;
private string myValueMember;
public Class_NameValue(string strNameMember,string stringValueMember)
{
this.myNameMember = strNameMember;
this.myValueMember = stringValueMember;
}
public string NameMember
{
get
{
return myNameMember;
}
}
public string IdMember
{
get
{
return myValueMember;
}
}
}
代码编译好了。但是当应用程序运行时,它会出错
“Cannot bind to the new display member.Parameter name: newDisplayMember
”
我的代码有什么问题?有人可以帮忙吗?
提前致谢。
答案 0 :(得分:2)
你需要设置
DataSource之前的DisplayMember和ValueMember属性。
像
MySqlDataReader rdr = cmd.ExecuteReader();
ArrayList temptbl = new ArrayList();
while (rdr.Read()){
temptbl.Add(new Class_NameValue(rdr.GetString(1), rdr.GetString(0)));
}
rdr.Close();
cmb_items.DisplayMember = "NameMember";
cmb_items.ValueMember = "IdMember";
cmb_items.DataSource = new BindingSource(temptbl, null);
还有一个技巧从
传递NameMember
和IdMember
temptbl.Add(new Class_NameValue(rdr.GetString(1),rdr.GetInt32(0)));
到
temptbl.Add(new Class_NameValue(NameMember = rdr.GetString(1).ToString(),IdMember = rdr.GetString(0).ToString()));
表示从此处设置属性value
而不是在类本身中。
请尝试..
希望它有效..
答案 1 :(得分:0)
尝试这样做:
var bs = new BindingSource(temptbl, null);
cmb_items.DataSource = bs;
cmb_items.DisplayMember = "yourDisplayMember";
cmb_items.ValueMember = "yourValueMember";