【问题标题】:How can I bind a ListBox to a List AND bind an int?如何将 ListBox 绑定到 List 并绑定 int?
【发布时间】:2013-12-29 10:59:21
【问题描述】:

我的表单上有几个 ListBox,每个对应一个双精度列表和一个整数。

我需要在每个 ListBox 的单击事件中使用与每个对应的 int。

所以,我希望列表框中的值与列表中的双精度值相对应,并在列表框中附加一个 int,我可以在点击事件中使用它。

我考虑过使用由 int 和 List<double> 组成的对象,但我相信这会取消绑定功能。

谁能建议我可以做到这一点的方法?

非常感谢任何建议。

【问题讨论】:

    标签: c# winforms binding listbox


    【解决方案1】:

    您可以使用每个ListBoxTag 属性来存储对应的整数值。示例代码:

    ListBox listBox1 = new ListBox();
    List<double> doubleList = new List<double>() {1.0, 1.2, 1.3 };
    int curInt = 1;
    listBox1.DataSource = doubleList;
    listBox1.Tag = curInt;
    listBox1.Click +=new EventHandler(listBox_Click);
    
    ListBox listBox2 = new ListBox();
    doubleList = new List<double>() { 2.0, 2.2, 2.3 };
    curInt = 2;
    listBox2.DataSource = doubleList;
    listBox2.Tag = curInt;
    listBox2.Click += new EventHandler(listBox_Click);
    
    this.Controls.Add(listBox1);
    this.Controls.Add(listBox2);
    

    然后你就可以很容易的在Click Event方法中得到对应的int值,方法如下:

    private void listBox_Click(object sender, EventArgs e)
    {
        ListBox curListBox = (ListBox)sender;
        int curInt = 0;
        if(curListBox.Tag != null) curInt = (int)curListBox.Tag;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-05-03
      • 1970-01-01
      • 2016-04-18
      • 2010-10-05
      • 2011-07-27
      • 1970-01-01
      • 2011-06-09
      • 1970-01-01
      • 2015-09-01
      相关资源
      最近更新 更多