This article will show you how you c an bind a asp.net listbox
control by an XML file data using dataset in C#.net.
Some of my previous articles are as follows: Stylish
RadioButton, DropdownList, ListBox and TextBox Control In Asp.Net Using Css,
Popup
Window Open Without Page Refresh in Asp.net MVC Using javaScript, Image
Save In XML and Load XML Bitmap Image File in Windows Application Using C#.Net,
How
to Save Record in XML File and Read XML to Display in DataGridview Using C#.net
in Windows Application, Transfer
Listbox Items to Another Listbox Using C#.Net and VB.Net | How to Move List Box
Items to another List Box in C#.
So for this article first we will create a new asp.net
application and add a xml file in it.
xml version="1.0" encoding="utf-8" ?>
<CountryModel>
<Country>
<id>1</id>
<name>India</name>
</Country>
<Country>
<id>2</id>
<name>Pakistan</name>
</Country>
<Country>
<id>3</id>
<name>Sri Lanka</name>
</Country>
<Country>
<id>4</id>
<name>Nepal</name>
</Country>
<Country>
<id>5</id>
<name>Bhutan</name>
</Country>
</CountryModel>
|
Now add a list box control in aspx page to bind the control.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1"
%>
<!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>Bind
Asp.net ListBox Control by XML File Data Using DataSet in C#.Net
Css</title>
<link href="Styles/Site.css" rel="stylesheet"
type="text/css"
/>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="100%" class="content">
<tr>
<td>
Country List
<br />
<asp:ListBox ID="ListBox1" runat="server" CssClass="selectbox" Height="50px">
</asp:ListBox>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
|
Now let’s check the code for bind xml data to the listbox
control.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected
void Page_Load(object
sender, EventArgs e)
{
if
(!IsPostBack)
{
GetData();
}
}
public
void GetData()
{
try
{
DataSet
dsResult = new DataSet();
dsResult.ReadXml(Server.MapPath("~/XML/XMLFile1.xml"));
if
(dsResult.Tables.Count != 0)
{
if
(dsResult.Tables[0].Rows.Count > 0)
{
ListBox1.DataSource =
dsResult.Tables[0];
ListBox1.DataTextField = "name";
ListBox1.DataValueField = "id";
ListBox1.DataBind();
}
}
}
catch
(Exception ex)
{
}
}
}
}
|
In above code I have read the xml file into data set and
bond the data set table to listbox datasource. After that I have assigned DataTextField
and DataValueField of listbox control.
Now we have done run the application to check the output.
0 comments:
Please let me know your view