Category >
ASP.NET
|| Published on :
Thursday, February 18, 2016 || Views:
10969
||
bind dropdown list with XML file in asp.net
Introduction
Here Pawan Kumar will explain How to bind dropdown list with XML file in asp.net?
Description
In previous post I have explained Show Asp.Net Gridview Row Details using Bootstrap Tooltip on MouseHover GridView Row Cell, Best 7 Resources for 3 tier architecture Asp.Net, Show Hide Password Using Javascript ASP.NET, How to Create Tab Control Using jQuery In Asp.Net, jQuery Datepicker Calendar With Slide Down Effect In Asp.Net, jQuery Code To Select Multiple Item By Pressing Ctrl Button In Asp.Net, and many more articles.
Now I will explain How to How to bind dropdown list with XML file in asp.net?
So follow the steps to learn How to bind dropdown list with XML file in asp.net?
Step 1: Create a website
Step 2: Create a XML file with name Departments.xml and save to root of the website.
<?xml version="1.0" encoding="utf-8" ?>
<Company>
<department>
<deptId>1</deptId>
<deptName>Finance</deptName>
</department>
<department>
<deptId>2</deptId>
<deptName>Human Resource</deptName>
</department>
<department>
<deptId>3</deptId>
<deptName>Information Technology</deptName>
</department>
<department>
<deptId>4</deptId>
<deptName>System Network</deptName>
</department>
<department>
<deptId>5</deptId>
<deptName>Customer Support</deptName>
</department>
</Company>
Step 3 : Add a new webpage and write the below codes:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sample binding xml file into dropdown list</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Department :
<asp:DropDownList ID="DrpDepartment" AutoPostBack="true" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>
Step 4: Add the following codes to code behind file.
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
LoadDropdownList();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
private void LoadDropdownList()
{
try
{
DataSet dsDept = new DataSet();
dsDept.ReadXml(Server.MapPath("Departments.xml"));
DrpDepartment.DataSource = dsDept;
DrpDepartment.DataTextField = "deptName";
DrpDepartment.DataValueField = "deptId";
DrpDepartment.DataBind();
DrpDepartment.Items.Insert(0, new ListItem("-- Select --", "0"));
}
catch (Exception ex)
{
throw ex;
}
}
}
Conclusion:
So, In this tutorial we have learned, How to bind dropdown list with XML file in asp.net?
Download Source Codes