Friday, 26 February 2016

How to save CheckBoxList item to DataBase in ASP.Net with C#

In this article, I will explain you how we can save CheckBoxList item data to DataBase in with C#.

Creating DataBase Table

First, we need to create table named as tbl_City to save items from CheckBoxList.

create table tbl_City
Id int identity,
City varchar(20)

In Designer File

In designer file, create a CheckBoxList control chblstCity and add some items. Create a Button Control to save item to DataBase.

<div align="center">
            <asp:Label ID="lblMessage" runat="server"></asp:Label>
            <asp:CheckBoxList ID="chblstCity" runat="server">
                <asp:ListItem Text="Mumbai" Value="1"></asp:ListItem>
                <asp:ListItem Text="Delhi" Value="2"></asp:ListItem>
                <asp:ListItem Text="Chennai" Value="3"></asp:ListItem>
                <asp:ListItem Text="kolkata" Value="4"></asp:ListItem>
           <asp:Button ID="btnSave" Text="Save To DataBase" OnClick="btnSave_Click" runat="server" />

Namespaces Used

Include the below Namespaces.

using System.Data;
using System.Data.SqlClient;

Complete C# Code

When page loads, CheckBoxList will be displayed along with items as you can see below.

How to save checkboxlist item to database in

Change your database connection string.

protected void Page_Load(object sender, EventArgs e)


        protected void btnSave_Click(object sender, EventArgs e)
            //iterating through CheckBoxList items
            foreach (ListItem li in chblstCity.Items)
                if (li.Selected)
                    //passing value
                    string Id = li.Value;
                    //passing text
                    string City = li.Text;
                    SaveCity(Id, City);

        public void SaveCity(string Id, string City)
            string connection = @"server=XXXX;database=XXXX;uid=XXXX;password=XXXX;";
            SqlConnection con = new SqlConnection(connection);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "insert into tbl_City values(@Id,@City)";
            cmd.Connection = con;
            cmd.Parameters.Add("@Id", SqlDbType.Int).Value = Convert.ToInt32(Id);
            cmd.Parameters.Add("@City", SqlDbType.VarChar).Value = City;
            lblMessage.Text = "Saved successfully!";
            lblMessage.ForeColor = System.Drawing.Color.Green;


Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive