Use C# to Populate Dropdown Lists With XML
Click here to see it work The code below opens an xml file, reads the data from the xml file, dynamically adds a label for the dropdown list, and adds the dropdown list to the asp.net page. After the dropdown lists are added to the screen, the dropdown lists are populated. The dropdown list is added to an asp Panel control named pnlMain.
C# Code (You will need to reference System.Xml and System.IO in order for this to work.)
private void LoadData(string sFile)
{
XmlTextReader reader = new XmlTextReader(sFile); //the file name is passed into the function
string sField = "";
string sID = "";
string sValue = "";
string sText = "";
string sLabel = "";
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
sField = reader.Name;
break;
case XmlNodeType.Text:
switch (sField)
{
case "ID": //get the ID for the dropdown from the xml file
sID = reader.Value;
break;
case "label":
sLabel = reader.Value; //get the label name from the xml file
Label lblHold = new Label();
lblHold.ID = "lbl" + sLabel;
lblHold.Text = sLabel;
pnlMain.Controls.Add(lblHold); //add the label to the panel control
DropDownList ddListHold = new DropDownList(); //declare the dropdown variable
ddListHold.ID = sID;
ddListHold.CssClass = "btn dropdown-toggle"; //add bootstrap formatting to the dropdown
ddListHold.BackColor = System.Drawing.ColorTranslator.FromHtml("#0E3FE7"); //optional color formatting
ddListHold.ForeColor = System.Drawing.Color.White; //optional color formatting
ddListHold.Width = 300; //set width of the dropdown
pnlMain.Controls.Add(new LiteralControl("< p>")); //add paragraph beginning tag
pnlMain.Controls.Add(ddListHold); //add the dropdown to the panel control
pnlMain.Controls.Add(new LiteralControl("< /p>")); //add paragraph ending tag
break;
case "value":
string[] s = reader.Value.Split('|'); //use the split function to retrieve the value and text for the dropdown items
sValue = s[0].ToString();
sText = s[1].ToString();
DropDownList ddListHold2 = (DropDownList)pnlMain.FindControl(sID); //find the previously added dropdown
ddListHold2.Items.Add(new ListItem(sText, sValue)); //add the list item to the previously added dropdown
break;
}
break;
case XmlNodeType.EndElement: //Display the end of the element.
break;
}
}
}
XML File Contents
< ddlists>
< dddata>
< ID>ddRegion< /ID>
< label>Region< /label>
< value>0|Select a Region< /value>
< value>1|East< /value>
< value>2|North< /value>
< value>3|South< /value>
< value>4|West< /value>
< /dddata>
< dddata>
< ID>ddRepresentative< /ID>
< label>Representative< /label>
< value>0|Select a Representative< /value>
< value>1|Jordan, Larry< /value>
< value>2|McNabb, Deion< /value>
< value>3|Rodgers,Brett< /value>
< value>4|Smith, John< /value>
< /dddata>
< /ddlists>
#CSharp #Bootstrap #XML