What is the proper way to load up a ListBox?

后端 未结 6 825
我寻月下人不归
我寻月下人不归 2020-12-05 05:00

What is the proper way to load a ListBox in C# .NET 2.0 Winforms?

I thought I could just bind it to a DataTable. No such luck.
I though

相关标签:
6条回答
  • 2020-12-05 05:12

    Using the DataSource paramater used to suck performance wise - on ComboBoxes at least,

    I am now heavily conditioned to override ToString() on the object and just adding the objects using the Items.AddRange() method, as another commenter above describes.

    0 讨论(0)
  • 2020-12-05 05:14

    You can bind a DataTable directly...

    listbox.ValueMember = "your_id_field";
    listbox.DisplayMember = "your_display_field";
    listbox.DataSource = dataTable;
    
    0 讨论(0)
  • 2020-12-05 05:18

    Simple code example. Say you have a Person class with 3 properties. FirstName, LastName and Age. Say you want to bind your listbox to a collection of Person objects. You want the display to show the first name, but the value to be the age. Here's how you would do it:

    List<Person> people = new List<Person>();
    people.Add(new Person { Age = 25, FirstName = "Alex", LastName = "Johnson" });
    people.Add(new Person { Age = 23, FirstName = "Jack", LastName = "Jones" });
    people.Add(new Person { Age = 35, FirstName = "Mike", LastName = "Williams" });
    people.Add(new Person { Age = 25, FirstName = "Gill", LastName = "JAckson" });
    this.listBox1.DataSource = people;
    this.listBox1.DisplayMember = "FirstName";
    this.listBox1.ValueMember = "Age";
    

    The trick is the DisplayMember, and the ValueMember.

    0 讨论(0)
  • 2020-12-05 05:18

    Lets assume your data type is called MyDataType. Implement ToString() on that datatype to determine the display text. e.g.:

    class MyDataType
    {
      public string ToString()
      {
        //return the text you want to display
      }
    }
    

    Then you can take a list consisting of your datatype and cram it into the ListBox via AddRange() as follows:

    ListBox l;
    List<MyDataType> myItems = new List<MyDataType>(); // populate this however you like
    l.AddRange(myItems.ToArray());
    

    Let me know if you need more help - it would help to know what datatype you are trying to display in the listbox.

    0 讨论(0)
  • 2020-12-05 05:19

    You can set the datasource to whatever datasource you like that implements the IList or IListSource.

    You will also need to set the DisplayMember and the ValueMember properties to the fields you want to display and have the values associated with respectively.

    0 讨论(0)
  • 2020-12-05 05:36

    To bind to a dictionary you have to wrap it in a new BindingSource object.

    MyListBox.DataSource = New BindingSource(Dict, Nothing)
    MyListBox.DisplayMember = "Value"
    MyListBox.ValueMember = "Key"
    
    0 讨论(0)
提交回复
热议问题