Load Drop Down List From Data Row



Published On Thursday June 4, 2020
Reading Time: < 1 minute

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();
}

 

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x