|
How to dynamically populate DropDownList
There are a lot of examples in .Net framework documentation that shows how to
use DropDownList control for displaying data in a drop down list.
Almost all the examples demonstrate populating the list using hard coded values
or ListItem controls.
<asp:DropDownList ID="NameDropDown" Runat="server">
<asp:ListItem>Source</asp:ListItem>
<asp:ListItem>Code</asp:ListItem>
</asp:DropDownList>
But sometime you ned to populate the list dynamically depending on if you have
any data for the list or not. And in some cases you may need to append more
items to hard coded list items. The following code shows you how to achieve
this.
[aspx]
<asp:DropDownList ID="NameDropDown" Runat="server">
</asp:DropDownList>
***********************************************************
[C#]
protected DataTable m_DataTable = null;
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
// Initialize DropDown List
m_DataTable = this.CreateDataTable();
this.InitializeNameDropDown(m_DataTable);
}
}
private void InitializeNameDropDown(DataTable dtTable)
{
int nTotalRecords = dtTable.Rows.Count;
for (int i = 0; i < nTotalRecords; i++)
{
NameDropDown.Items.Add(dtTable.Rows[i]["Title"].ToString());
}
}
If you have some hard coded ListItems added to the list, then the
dynamically added items get appended at the end of the list.
|