ASP:Listbox – How To Populate a Listbox from a C# Generic List
Filed under: ASP:NET, C#, Internet | Tags: ASP, c sharp, C#, listbox, vb, vb.net |
The guys over at ASPAlliance did an excellent article on user the ASP:ListBox with VB.NET. The article can be viewed at ASPAlliance. Which is really great if you are using VB.NET. The article makes it very easy to modify for use with C#.
Listbox web server control is equivalent to the <Select> tag in HTML. This control will be very useful to get inputs from user, were all values are pre-defined. For eg: inorder to accept the “State in which the user is living”, we can have a list of all states available. In this session, we will learn how to populate a listbox control.
Listbox – How to populate a Listbox from a List Generic.
Populating a listbox from an existing C# List Generic is very easy.
| <%@ Import Namespace=”System.Collections.Generic” %> <script language=”c#” runat=”server”> private List<MyList> thelist; protected void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) this.BindData(); }private void BindData() { // code to populate listbox from generic list MyCollection mc = new MyCollection(); \\ this is where my getStates function is. thelist = mc.getStates(); foreach (MyList v in thelist) <html> <asp:ListBox ID=”mylist” runat=”server”></asp:ListBox> |
This is not the only way to do this. One thing I didn’t point out is that I had to filter out certain records. His original looked more like this…
foreach (MyList v in thelist)
{
if ( v.StateCode != “SC” || v.StateCode != “NC” )
{
ListItem li = new ListItem();
li.Value = v.StateCode;
li.Text = v.StateName;
mylist.Items.Add(li);
li = null;
}
}