Introduction
It is a common and repetitive task in web application development that a developer has to bind data to a DropDownList, a ListBox, a CheckBoxList, a RadioButtonList, or a BulletedList. Data can be programmatically bound to a DropDownList control using the following code:
DropDownList1.DataSource = SomeDataSourc;
DropDownList1.DataValueField = ValueDataName;
DropDownList1.DataTextField = TextDataName;
DropDownList1.DataBind();
Similarly, you can bind data to a ListBox, a CheckBoxList, a RadioButtonList, or a BulletedList by replacing the control ID DropDownList1 in the above code with another control ID, such as ListBox1, CheckBoxList1, etc. As you can see, similar code needs to be repeated five times when binding to each of the controls. Although .NET Framework makes it easy enough, it is still a lot of work to write similar code over and over dealing with each individual control. It would be nice if we can use one piece of code to handle all five controls, no matter which one is used.
In this article, I present you with a generic class: the ListAssistant class, which serves the purpose of handling all the above mentioned controls with one piece of code. Hope that you can benefit from this class.
ListAssistant Class
With finding a generic way in mind, I dug into MSDN library as well as other reference sources on the internet. It turned out that the .NET Framework provides a way for us to do it. The key is in the parent class, ListControl, under the System.Web.UI.WebControls namespace, from which the DropDownList, ListBox, CheckBoxList, RadioButtonList, and BulletedList controls are derived.
The ListAssistant class chooses to work the ListControl class instead of dealing with the DropDownList, ListBox, CheckBoxList, RadioButtonList, and BulletedList controls directly. A DropDownList control (or any other) can be passed into the ListAssistant class from a calling ASP.NET page, wherever needed. This resolves our problem of writing similar code repeatedly for this group of controls so as to handle them with one piece of generic code.
The code for the ListAssistant class is straightforward and easy to understand, and is shown below:
using System;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
public class ListAssistant
{
public ListAssistant()
{
}
public void PopulateList(System.Web.UI.WebControls.ListControl list,
string valueDataName, string textDataName,
DataTable dataTable)
{
list.DataSource = dataTable;
list.DataValueField = valueDataName;
list.DataTextField = textDataName;
list.DataBind();
if (list.GetType().ToString().IndexOf("DropDownList")>-1)
{
list.Items.Add(new ListItem("", ""));
list.SelectedIndex =
list.Items.IndexOf(list.Items.FindByValue(""));
}
}
public string GetListSelections(System.Web.UI.WebControls.ListControl list,
string collectValueOrText)
{
ListItemCollection ListItems = list.Items;
string SelectedItems = "";
foreach (ListItem itm in ListItems)
{
if (itm.Selected)
{
if (collectValueOrText.ToLower() == "value")
SelectedItems += itm.Value + ", ";
else
SelectedItems += itm.Text + ", ";
}
}
if (SelectedItems.Length > 0)
{
SelectedItems = SelectedItems.Substring(0, SelectedItems.Length - 2);
}
return SelectedItems;
}
public void SetListSelections(System.Web.UI.WebControls.ListControl list,
string csvValueString)
{
list.ClearSelection();
string[] SelectedItem = csvValueString.Split(new char[] { ',' });
for (int i = 0; i < SelectedItem.Length; i++)
{
foreach (ListItem itm in list.Items)
{
if (itm.Value.ToLower() == SelectedItem[i].Trim().ToLower())
{
itm.Selected = true;
}
}
}
}
}
There are three methods in the class: PopulateList(), GetListSelections(), and SetListSelections(). The method names imply what they do, which are the regular operations of these controls in a web application.
The first parameter in all three methods is of the type System.Web.UI.WebControls.ListControl, which makes it possible that any one of DropDownList, ListBox, CheckBoxList, RadioButtonList, or BulletedList can be passed in at runtime. PopulateList() has three more parameters. The last parameter is of type DataTable that is used as the data source for a list. The other two parameters, valueDataName and textDataName, indicate the field names from the DataTable used for the value and text pair in a list. With these two parameters, any field in the DataTable can be specified to populate a list. The method simply does data binding for the controls. However, additional code is used to identify a DropDownList control in order to add an empty item. GetListSelections() returns a comma or tab separated string representing items selected in a control. The second parameter could be “text” or “tab”, indicating if a text string or a value string should be returned. SetListSelections() sets up the item selections for an existing list that is populated already.
How to Use the ListAssistant Class
I prepared a demo application to use the ListAssistant class, which is available for download.
The application mainly consists of the ListAssistant class and the ListDemo.aspx page. The ASPX page holds a DropDownList, a ListBox, a CheckBoxList, a RadioButtonList, and a BulletedList control, and several buttons that trigger the events to display item selections or set up item selections. There are several TextBoxes in which comma separated values can be entered. This page illustrates the initial data binding to the list controls, displaying item selections upon a button click, and setting up the item selections with comma separated values entered in the TextBoxes.
The code is self explanatory. The list controls are initially populated in the Page_Load event.
DataTable DTbl = CreateDataTable();
ListAssistant Lst = new ListAssistant();
Lst.PopulateList(ListBox1, "Col0_Name", "Col2_Name", DTbl);
Lst.PopulateList(DropDownList1, "Col0_Name", "Col2_Name", DTbl);
Lst.PopulateList(CheckBoxList1, "Col0_Name", "Col2_Name", DTbl);
Lst.PopulateList(RadioButtonList1, "Col0_Name", "Col2_Name", DTbl);
Lst.PopulateList(BulletedList1, "Col0_Name", "Col2_Name", DTbl);
For demo purpose, a DataTable is created programmatically with three columns and five rows. In real world, the DataTable can be filled with any type of data source, for instance, a database query, an XML file, an Excel worksheet, etc. To populate a control, simply pass the control ID, the DataTable, and two column names as the value and text pairs for the control into the PopulateList() method.
To retrieve the item selections from these controls, the GetListSelections() method is called. In this application, it is done inside a button click event. The comma separated selection strings built by the method call are then displayed on the page with several Label controls. As shown in the following code, the parameter “target” specifies if the selected values or the selected texts should be retrieved.
ListAssistant lst = new ListAssistant();
lblListBoxSelected.Text = lst.GetListSelections(ListBox1, target);
lblDropDownSelected.Text = lst.GetListSelections(DropDownList1, target);
lblCheckBoxSelected.Text = lst.GetListSelections(CheckBoxList1, target);
lblRadioButtonSelected.Text = lst.GetListSelections
(RadioButtonList1, target);
Another common task in handling these controls is setting up (or pre-setting) the item selections in each control programmatically. The SetListSelections() method does just that. For demo purpose, a comma separated value string for each control is entered in a TextBox, as indicated in the code below:
ListAssistant Lst = new ListAssistant();
Lst.SetListSelections(ListBox1, txtListBoxSelection.Text);
Lst.SetListSelections(CheckBoxList1, txtCheckBoxSelection.Text);
Lst.SetListSelections(DropDownList1, txtDropDownSelection.Text);
Lst.SetListSelections(RadioButtonList1, txtRadioButtonSelection.Text);
As seen in this demo, the use of the ListAssistant class is very simple and straightforward. It is clear that regular data binding and handling for these controls can be easily performed with the ListAssistant class, which makes programming really easy.
Summary
I have introduced a ListAssistant class in this article to illustrate how the DropDownList, ListBox, CheckBoxList, RadioButtonList, and BulletedList controls can be handled with one generic class. You can easily modify the class to meet your specific business needs. For example, you may add an overloaded method for PopulateList() by passing a different data source in addition to a DataTable, or by removing textDataName and valueDataName and always binding data with the first and the second columns in the DataTable (.Columns[0].ColumnName and .Columns[1].ColumnName), etc. My intent was to present you with an idea. The existing methods here might be far from what you need. Please feel free to use and modify the code for your own purpose. Your comments are appreciated.