4

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

0

1 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to bind, but still read back the whole class instance? Let's say I wanted to retrieve the actual text that was selected, instead of the Id (while keeping Id as the value member), could I do so?
@McAdam331: yes, just don't set anything as ValueMember. In this way listBox1.SelectedValue property will be of type MyClass.
Awesome! I was hoping you still used your account, I can really apply this to a project I'm working on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.