In this example, I will show you to bind dropdownlist with an xml file using ReadXml() method. In order to read data from cities.xml file into a dataset from the specified path using Server.MapPath.
Step 1: Create an XML file:
Right click on the project and add xml file and name it as cities.xml. Copy and paste the following code.
<?xml version="1.0" encoding="utf-8" ?>
<cities>
<City>
<CityId>101</CityId>
<CityName>London</CityName>
</City>
<City>
<CityId>102</CityId>
<CityName>Bangkok</CityName>
</City>
<City>
<CityId>103</CityId>
<CityName>Paris</CityName>
</City>
<City>
<CityId>104</CityId>
<CityName>Dubai</CityName>
</City>
<City>
<CityId>105</CityId>
<CityName>Istanbul</CityName>
</City>
</cities>
Step 2: Drag a DropDownList from toolbox and drop it on the webform.Copy and paste the following code.
WebControls.aspx:
<table style="font-family: Arial;">
<tr>
<td colspan="2"><b>Register Form</b></td>
</tr>
<tr>
<td>First Name: </td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Last Name: </td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Country:</td>
<td>
<asp:DropDownList ID="ddlCities" Width="173px" runat="server">
</asp:DropDownList>
</td>
</tr>
</table>
Step 2: Copy and paste the following code in the code behind page.
WebControls.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCitiesDropDownList();
}
}
public void LoadCitiesDropDownList()
{
//Create a new DataSet
DataSet ds = new DataSet();
//Read the xml data from the XML file using ReadXml() method
ds.ReadXml(Server.MapPath("Cities.xml"));
ddlCities.DataTextField = "CityName";
ddlCities.DataValueField = "CityId";
ddlCities.DataSource = ds;
ddlCities.DataBind();
ListItem li = new ListItem("Select City", "-1");
ddlCities.Items.Insert(0, li);
}
Output:
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article