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 get domain name information from a Domain using Python
- ModulenotFoundError: no module named 'debug_toolbar' -SOLUTION
- How to create superuser in django project hosted in cPanel without terminal
- CSS & images not loading in django admin | cpanel without terminal
- Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects
- How to sell domain name on Godaddy (2023)
- TemplateSyntaxError at / Could not parse the remainder: ' + 1' from 'forloop.counter0 + 1'
- urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0
Related Article