0

你们中的一些人可能认为它已经在这个社区的其他地方解决了,但我无法真正解决它。我有一个 ComboBox,我喜欢使用 DataReader 填充它。像往常一样,我创建了一个类来获取设置value memberdisplay 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

我的代码有什么问题?有人可以帮忙吗?

提前致谢。

4

2 回答 2

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);

还有一个技巧 pass the NameMemberand IdMemberfrom

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从这里设置属性而不是在类本身中。请试试..

希望它有效..

于 2013-05-09T10:01:47.007 回答
0

尝试这样做:

var bs = new BindingSource(temptbl, null);
cmb_items.DataSource = bs;
cmb_items.DisplayMember = "yourDisplayMember";
cmb_items.ValueMember = "yourValueMember";
于 2013-05-09T10:47:35.313 回答