将列表框内容绑定到另一个列表框

时间:2012-09-05 11:01:20

标签: c#

我的表单中有2个列表框,我将一些数据绑定到数据库的第一个列表框中。现在,我必须在按下按钮时在第二个列表框中显示第一个列表框的选定项目。我能够一次显示一个选定的项目,但我无法显示多个选定的项目。我使用了一个哈希表和下面的代码,请提前感谢我对这个概念的新见解。

Hashtable ht = new Hashtable();
ht.Add(listbox1.SelectedValue.ToString(),listbox1.Text.ToString());
int i = 0;
foreach (string ent in ht.Values)
{   
    string[] name = new string[listbox1.Items.Count];
    for (i = 0; i < listbox1t.SelectedItems.Count; i++)
    {     
        name[i] = listbox1.Text;
        this.listbox2.Items.Add(name[i]);
    } 
    listbox2.DisplayMember = ht.Values.ToString();
    listbox2.ValueMember = ht.Keys.ToString();
}

2 个答案:

答案 0 :(得分:0)

DisplayMember不是应该显示的内容,而是为Items集合中的每个对象评估的属性的名称。因此,举例来说,代表客户的对象是FullNameMSDN link,例如包含)。

ValueMember应包含唯一标识对象的属性的名称,例如CustomerId

答案 1 :(得分:0)

将列表作为数据源分配给第一个listcontrol:

listBoxControl1.Datasource = new List<string>() {"one","two","three","four"};

并在selectedvaluechanged事件中......

var tmp = listBoxControl1.SelectedItems.Cast<string>();
listBoxControl2.datasource = tmp.ToList<string>();

应该有用......

我使用字符串作为示例,您应该转换为您使用的类。 并且...在构造函数中指定displayvalue和valuemember,无需多次执行。