【问题标题】:C#: easiest way to populate a ListBox from a ListC#:从列表中填充列表框的最简单方法
【发布时间】:2011-05-18 07:17:18
【问题描述】:

如果我有一个字符串列表,例如:

List<string> MyList = new List<string>();
MyList.Add("HELLO");
MyList.Add("WORLD");

有没有一种简单的方法可以使用 MyList 的内容来填充 ListBox?

【问题讨论】:

    标签: c# winforms list listbox


    【解决方案1】:

    试试:

    List<string> MyList = new List<string>();
    MyList.Add("HELLO");
    MyList.Add("WORLD");
    
    listBox1.DataSource = MyList;
    

    看看ListControl.DataSource Property

    【讨论】:

      【解决方案2】:

      这也是在 ListBox 中添加项目的最简单方法。

      for (int i = 0; i < MyList.Count; i++)
      {
              listBox1.Items.Add(MyList.ElementAt(i));
      }
      

      此代码的进一步即兴创作可以在运行时添加项目。

      【讨论】:

        【解决方案3】:

        你也可以使用AddRange方法

        listBox1.Items.AddRange(myList.ToArray());
        

        【讨论】:

          【解决方案4】:

          这是你要找的东西吗:

          myListBox.DataSource = MyList;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-06-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多