Bind Checkboxlist to xml file in asp.net

How to bind asp.net checkboxlist to xml file using dataset

This asp.net C# example is about checkboxlist binding to xml file using dataset
Now we create an xml file. We have named the xml file as states.xml. This xml file contains some states name from india. This  states will be populated to dropdownlist using asp.net c#
To create xml file open website menu ,select add new item, select xml file name it as states.xml,save it in root folder.After creating the xml file add below markup to states.xml



In the .aspx page add the checkboxlist control. In the designer page we have named the checkboxlist control as cblStatesThe name of the state will be assigned to text part and id will be assigned to value part of asp.net check box list control

Complete Aspx Code

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">

     <asp:CheckBoxList ID="cblStates" runat="server">
     </asp:CheckBoxList>
  
    </form>
</body>
</html>


To bind the dropdownlist to xml file we have created a method in page load method and named it as BindXmlToCheckBoxList().

Complete c# code

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 XMLExamples
{
    public partial class CheckBoxListExample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindXmlToCheckBoxList();
            }
        }

        private void BindXmlToCheckBoxList()
        {
            string filePath = Server.MapPath("~/States.xml");
            using (DataSet ds = new DataSet())
            {
                ds.ReadXml(filePath);

                cblStates.DataSource = ds;
                cblStates.DataTextField = "name";
                cblStates.DataValueField = "id";
                cblStates.DataBind();
                
            }
        }
    }
}

0 comments:

Post a Comment