Bind values from a list array to listbox
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.
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.
Hari Gillala
I am developer working with .Net technologies. Lately I been working on ASP.NET MVC with WCF. I am involved in full SDLC of the projects. I have passion for programming. Currently I am working for Swinton Insurance, Manchester
Updated on January 13, 2020Comments
-
Hari Gillala over 4 years
Could any body give a short example for binding a value from list array to listbox in c#.net
-
AdamMc331 almost 10 yearsIs 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?
-
digEmAll almost 10 years@McAdam331: yes, just don't set anything as
ValueMember
. In this waylistBox1.SelectedValue
property will be of typeMyClass
. -
AdamMc331 almost 10 yearsAwesome! I was hoping you still used your account, I can really apply this to a project I'm working on.