Published On Thursday June 4, 2020Reading Time: < 1minute
Creating a dynamic drop down list from DataRow returning from database i.e automatically binding the asp drop-down list field with the data returned from the database.
Returning Dictionary From Database:
public Dictionary<string, string> LoadDropDownList() {
var dictionary = new Dictionary<string, string> ();
DataTable res = new DataTable();
if (res.Rows.Count > 0) {
foreach(DataRow dr in res.Rows) {
dictionary.Add(dr["value"].ToString(), dr["text"].ToString());
}
}
return dictionary;
}
Call DDL Function:
PopulateDdl(ref ddlField, Dictionary);
PopulateDdl Function Description:
private void PopulateDdl(ref DropDownList ddl, Dictionary < string, string > dic, string selectedValue = null) {
List < ListItem > list = new List < ListItem > ();
foreach(var item in dic) {
if (selectedValue != null && item.Value.ToLower().Equals(selectedValue.ToLower())) {
list.Add(new ListItem {
Text = item.Value, Value = item.Key, Selected = true
});
} else {
list.Add(new ListItem {
Text = item.Value, Value = item.Key
});
}
}
ddl.DataTextField = "text";
ddl.DataValueField = "value";
string hasval = "";
if (selectedValue != null) {
dic.TryGetValue(selectedValue, out hasval);
if (hasval != "") {
ddl.SelectedValue = selectedValue;
}
}
ddl.DataSource = list;
ddl.DataBind();
}