Asp.net dropdownlist xmldatasource: In this tutorial, I am going to show you "how to bind XML data to dropdownlist in asp.net". Mainly we fetch data from Database but sometimes as per requirement, we want to fetch data from other data source like XML(xmldatasource). Don't worry I am here to tell you how you can bind asp.net dropdown list from the XML file.
asp net dropdownlist xmldatasource |
Steps to read XML file by tag name and BInd it with asp.net gridview
1. Add XML file (Visual C#).
2. Insert Data in the XML file with a specific tag. (See Below)
3. Give Server.MapPath correct.
4. Bind the dropdown with DataValueField and DataTextField.
Step 1:
Right Click on the project
-->Add
-->Add New item
-->Find XML File with Visual C# (See In Picture)
Countries.xml (File Name)
<?xml version="1.0" encoding="utf-8" ?>
<countries>
<country>
<cid>1</cid>
<cname>India</cname>
</country>
<country>
<cid>2</cid>
<cname>Pakistaan</cname>
</country>
<country>
<cid>3</cid>
<cname>USA</cname>
</country>
<country>
<cid>4</cid>
<cname>UK</cname>
</country>
<country>
<cid>4</cid>
<cname>Nepal</cname>
</country>
</countries>
ASPX Form
<table>
<tr>
<td>Country :</td>
<td>
<asp:DropDownList ID="ddlcountry" runat="server"></asp:DropDownList></td>
</tr>
</table>
Code Behind File (Cs page)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Fill_Country();
}
}
public void Fill_Country()
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("Countries.xml"));
ddlcountry.DataValueField = "cid";
ddlcountry.DataTextField = "cname";
ddlcountry.DataSource = ds;
ddlcountry.DataBind();
ddlcountry.Items.Insert(0, new ListItem("--select--", "0"));
}
Thanks for reading. If you have any doubt please feel free to comment below.
Post a Comment