Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind values from a list array to listbox

Could any body give a short example for binding a value from list array to listbox in c#.net

like image 648
Hari Gillala Avatar asked Oct 15 '25 23:10

Hari Gillala


1 Answers

It depends on how your list array is.

Let's start from an easy sample:

List<string> listToBind = new List<string> { "AA", "BB", "CC" };
this.listBox1.DataSource = listToBind;

Here we have a list of strings, that will be shown as items in the listbox.

alt text

Otherwise, if your list items are more complex (e.g. custom classes) you can do in this way:

Having for example, MyClass defined as follows:

public class MyClass
{
    public int Id { get; set; }
    public string Text { get; set; }
    public MyClass(int id, string text)
    {
        this.Id = id;
        this.Text = text;
    }
}

here's the binding part:

List<MyClass> listToBind = new List<MyClass> { new MyClass(1, "One"), new MyClass(2, "Two") };
this.listBox1.DisplayMember = "Text";
this.listBox1.ValueMember = "Id"; // optional depending on your needs
this.listBox1.DataSource = listToBind;

And you will get a list box showing only the text of your items. Setting also ValueMember to a specific Property of your class will make listBox1.SelectedValue containing the selected Id value instead of the whole class instance.

N.B.
Letting DisplayMember unset, you will get the ToString() result of your list entries as display text of your ListBox items.

alt text

like image 82
digEmAll Avatar answered Oct 18 '25 18:10

digEmAll