How to Populate ComboBox ListBox in ASP.Net

There are many different ways to populate the combo box control or list box control in C#. Here I will explain two different ways to populate the controls and get the selected values from them.

To Bind IList direct to the Data Source.

UC_ListBox.DisplayMember = “Name”;

UC_ListBox.ValueMember = “ID”;

UC_ListBox.DataSource = dao.GetListOfAllLesson();

Where GetListOfAllLesson is declared as:

Public IList<Lesson> GetListOfAllLesson()

{

var list = from l in linqDataContext.Lesson

orderby l.Date

select l;

return list.ToList<Lesson>();

}

Here, We can directly use the code with the Data Source of the control using.

UC_ListBox.DisplayMember = “Name”;

UC_ListBox.ValueMember = “ID”;

UC_ListBox.DataSource = from l in linqDataContext.Lesson

orderby l.Date

select l;

If we need to just get the two attributes(ID,Name) of the object rather then the whole object then we could use something like…

UC_ListBox.DisplayMember = “Name”;

UC_ListBox.ValueMember = “ID”;

UC_ListBox.DataSource = from l in linqDataContext.Lesson

orderby l.Date

select new {

ID = l.ID,

Text = l.Name

};

For getting the selected index or value use the following code, similarly, it also expose many other properties and events.

string value = UC_ListBox.SelectedValue;

string index = UC_ListBoxSelectedIndex;

string text = UC_ListBoxSelectedText;

There is another way to populate the controls and getting the selected values using the ListItem class, this class can be found in the following name space.

System.Web.UI.WebControls;

Dictionary<int, string> list = dao.GetListOfLesson();

foreach (var l in list)

{

ListItem item = new ListItem();

item.Text = l.Value;

item.Value = l.Key.ToString();

UC_ListBox.Items.Add(item);

}

public static Dictionary<int, string> GetListOfLesson()

{

Dictionary<int, string> dic = new Dictionary<int, string>();

var list = from l in linqDataContext.Lesson

orderby l.Date

select new

{

ID = l.ID,

Text = String.Format(“{0} : {1}”, l.Time,l.Date)

};

foreach (var l in list)

{

dic.Add(l.ID, l.Text);

}

return dic;

}

To get the selected values from the combo control, using SelectedItem object in the control and cast into the ListItem and then get the Index, text or even selected value.

string value = ((ListItem)LaSelector.SelectedItem).Value;

string txt = ((ListItem)LaSelector.SelectedItem).Text

Advertisements

One thought on “How to Populate ComboBox ListBox in ASP.Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s