Thursday, September 18, 2008

Fill asp.net DropdownList and ListBox controls with DataSource programmatically

DropdownList and Listbox both are asp.net data controls. They can be directly bound to a data source. But often programmers choose to fill them dynamically using code (in C# or VB.NET !).

I am listing the simple trick to programmatically bind asp.net DropdownList and ListBox controls.

Lets say myTable is the DataTable filled from the method FillMyDataTable. Now we can
start out the journey.

public void FillDropdownList()
{
DataTable table = new DataTable();
table = FillMyDataTable(); //a method that returns required DataTable in our case
dropdownlistDDL.DataSource = table;
dropdownlistDDL.DataValueField = "myID_Column";
dropdownlistDDL.DataBind();
}


Here dropdownlistDDL is the DropdownList and myID_Column is the field to be filled in
our DropdownList.

Now we are going to bind an asp.net ListBox control to the DataTable.

public void FillListBox()
{
DataTable table = new DataTable();
table = FillMyDataTable(); //a method that returns required DataTable in our case
listboxLB.DataSource = table;
listboxLB.DataValueField = "myID_Column";
listboxLB.DataBind();
}


Here listboxLB is the ListBox and myID_Column is the field to be filled in our ListBox.

We see that both the asp.net ListBox and DropdownList controls follow the same pattern
of binding to a data source programmatically.

Happy Programming!
kick it on DotNetKicks.com

0 comments:

Post a Comment

Hope you liked this post. You can leave your message or you can put your valuable suggestions on this post here. Thanks for the sharing and cooperation!

Popular Posts

Recent Articles