How to Bind Get Selected Checked CheckBoxList Items in GridView Edit Mode using Asp.Net C# VB.Net

Most of the Asp.net (C# or VB.Net) developers faced a problem when they want to implement edit functionality within a GridView. The problem is developers can not understand how to populate or Bind data into CheckBoxList within the GridView in Edit Mode. The another problem is after populating how to display or show current database value by default in CheckBoxList as a Selected Value in edit mode. In this example I will give you a complete solution on “How to operate CheckBoxList in GridView Edit Mode

Objective/Outcome:
How to Bind Get Selected Checked CheckBoxList Items in GridView Edit Mode using Asp.Net CSharp VB.Net

To do the Example First Create 2 Database Tables:

CREATE TABLE [dbo].[Brand](
	[ID] [bigint] NOT NULL,
	[Name] [varchar](max) NOT NULL,
 CONSTRAINT [PK_Brand] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[Product](
	[ID] [bigint] NOT NULL,
	[Name] [varchar](max) NULL,
	[Description] [varchar](max) NULL,
	[BrandID] [bigint] NULL,
 CONSTRAINT [PK_Product_2] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Now Insert Some Data:

INSERT INTO Brand Values(1,'Kohinoor')
INSERT INTO Brand Values(2,'Proctor & Gamble')
INSERT INTO Brand Values(3,'Telenor')
INSERT INTO Brand Values(4,'Unilever')

INSERT INTO PRODUCT VALUES(1,'Lux Beauty Soap','Product of Unilever',4)
INSERT INTO PRODUCT VALUES(2,'Tibbet Pomed','Winter Product',1)
INSERT INTO PRODUCT VALUES(3,'Data SIM','Subscriber Identity Module',3)
INSERT INTO PRODUCT VALUES(4,'Nippon','Color Television',1)

Now modify the Web.Config File to Connect to Database:

<configuration>
  <connectionStrings>
    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data Source=XXX.com;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->
  </connectionStrings>
...................
...................

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

Now add the GridView Control like Below:

<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" 
        AutoGenerateColumns="False" onrowdatabound="GridView1_RowDataBound" 
        onrowupdating="GridView1_RowUpdating" 
        onrowcancelingedit="GridView1_RowCancelingEdit" 
        onrowediting="GridView1_RowEditing" 
HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
         <Columns>
             <asp:BoundField DataField="Name" HeaderText="Name"/>
             <asp:BoundField DataField="Description" HeaderText="Description" />
              
             <asp:TemplateField HeaderText="Brand">
             <ItemTemplate>
             <asp:Label ID="lblBrand" runat="server" Text='<%#Eval("Brand") %>'>
             </asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
                 <asp:CheckBoxList ID="CheckBoxList1" runat="server">
                 </asp:CheckBoxList>
             </EditItemTemplate>
             </asp:TemplateField>
              
             <asp:CommandField ShowEditButton="True" />            
        </Columns>
        </asp:GridView>

Note: If you look at the GridView events you will get onrowdatabound, onrowupdating, onrowediting, onrowcancelingedit events. Each has individual purpose. Like onrowdatabound event will fire when GridView DataBind() method was called, onrowediting event will fire when user click on Edit link, onrowupdating event will fire when user click on Update link & onrowcancelingedit will fire when user click on Cancel link. Keep in mind in every event we need to rebind the GridView

Note: Don’t forget to add “System.Data”, “System.Data.SqlClient”, “System.Configuration” namespaces.

Now first Bind or Load the GridView Control:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            Bind_CheckBoxList();
    }

    private void Bind_CheckBoxList()
    {
        DataTable dt;
        String SQL = "SELECT P.ID ID, P.Name Name, P.Description Description, B.ID BrandID,B.Name Brand" +
                    " FROM Product P, Brand B" +
                    " WHERE P.BrandID=B.ID";


        string sConstr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(sConstr))
        {
            using (SqlCommand comm = new SqlCommand(SQL, conn))
            {
                conn.Open();
                using (SqlDataAdapter da = new SqlDataAdapter(comm))
                {
                    dt = new DataTable("tbl");
                    da.Fill(dt);
                }
            }
        }
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Bind_CheckBoxList()
        End If
    End Sub

    Private Sub Bind_CheckBoxList()
        Dim dt As DataTable
        Dim SQL As String = "SELECT P.ID ID, P.Name Name, P.Description Description, B.ID BrandID,B.Name Brand" +
                    " FROM Product P, Brand B" +
                    " WHERE P.BrandID=B.ID"


        Dim sConstr As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
        Using conn As SqlConnection = New SqlConnection(sConstr)
            Using comm As SqlCommand = New SqlCommand(SQL, conn)
                conn.Open()
                Using da As SqlDataAdapter = New SqlDataAdapter(comm)
                    dt = New DataTable("tbl")
                    da.Fill(dt)
                End Using
            End Using
        End Using

        GridView1.DataSource = dt
        GridView1.DataBind()
    End Sub

Now we need to implement each events that we have declared in GridView:
C# Code:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                CheckBoxList chkBrand = (CheckBoxList)e.Row.FindControl("CheckBoxList1");
                DataTable dt;
                String SQL = "SELECT * FROM Brand";

                string sConstr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(sConstr))
                {
                    using (SqlCommand comm = new SqlCommand(SQL, conn))
                    {
                        conn.Open();
                        using (SqlDataAdapter da = new SqlDataAdapter(comm))
                        {
                            dt = new DataTable("tbl");
                            da.Fill(dt);
                        }
                    }
                }

                chkBrand.DataSource = dt;
                chkBrand.DataTextField = "Name";
                chkBrand.DataValueField = "ID";
                chkBrand.DataBind();
                chkBrand.SelectedValue = ((DataRowView)e.Row.DataItem)["BrandID"].ToString();
            }
        }
    }

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string sConstr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(sConstr))
        {
            //string sUpdateSQL = "UPDATE Product SET BrandID=@BrandID WHERE ID=@ID";
            //conn.Open();
            //SqlCommand cmd = new SqlCommand(sUpdateSQL, conn);
            //cmd.Parameters.AddWithValue("@BrandID", ((CheckBoxList)GridView1.Rows[e.RowIndex].FindControl("CheckBoxList1")).SelectedValue);
            //cmd.Parameters.AddWithValue("@ID", GridView1.DataKeys[e.RowIndex].Value);
            //cmd.CommandType = CommandType.Text;
            //cmd.ExecuteNonQuery();

            //Response.Write(((CheckBoxList)GridView1.Rows[e.RowIndex].FindControl("CheckBoxList1")).SelectedValue);

            foreach (ListItem oItem in ((CheckBoxList)GridView1.Rows[e.RowIndex].FindControl("CheckBoxList1")).Items)
            {
                if (oItem.Selected)
                {
                    // Here you will get all CheckBoxList Selected Items
                    // You can do any operation as you like
                    // For simplicity just printed the value
                    Response.Write(oItem.Value + "|");
                }
            }
            
            GridView1.EditIndex = -1;
            Bind_CheckBoxList();
        }
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        Bind_CheckBoxList();
    }


    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        Bind_CheckBoxList();
    }

Note: GridView1.EditIndex = -1 has special meaning. Remove the line & see the output.

VB.Net Code:

    Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then
            If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
                Dim chkBrand As CheckBoxList = DirectCast(e.Row.FindControl("CheckBoxList1"), CheckBoxList)
                Dim dt As DataTable
                Dim SQL As [String] = "SELECT * FROM Brand"

                Dim sConstr As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
                Using conn As New SqlConnection(sConstr)
                    Using comm As New SqlCommand(SQL, conn)
                        conn.Open()
                        Using da As New SqlDataAdapter(comm)
                            dt = New DataTable("tbl")
                            da.Fill(dt)
                        End Using
                    End Using
                End Using

                chkBrand.DataSource = dt
                chkBrand.DataTextField = "Name"
                chkBrand.DataValueField = "ID"
                chkBrand.DataBind()
                chkBrand.SelectedValue = DirectCast(e.Row.DataItem, DataRowView)("BrandID").ToString()
            End If
        End If
    End Sub

    Protected Sub GridView1_RowEditing(sender As Object, e As GridViewEditEventArgs)
        GridView1.EditIndex = e.NewEditIndex
        Bind_CheckBoxList()
    End Sub

    Protected Sub GridView1_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
        Dim sConstr As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString

        'Using conn As New SqlConnection(sConstr)
        '    Dim sUpdateSQL As String = "UPDATE Product SET BrandID=@BrandID WHERE ID=@ID"
        '    conn.Open()
        '    Dim cmd As New SqlCommand(sUpdateSQL, conn)
        '    cmd.Parameters.AddWithValue("@BrandID", DirectCast(GridView1.Rows(e.RowIndex).FindControl("CheckBoxList1"), CheckBoxList).SelectedValue)
        '    cmd.Parameters.AddWithValue("@ID", GridView1.DataKeys(e.RowIndex).Value)
        '    cmd.CommandType = CommandType.Text
        '    cmd.ExecuteNonQuery()
        '    GridView1.EditIndex = -1
        '    Bind_CheckBoxList()
        'End Using

        For Each oItem As ListItem In CType(GridView1.Rows(e.RowIndex).FindControl("CheckBoxList1"), CheckBoxList).Items
            If oItem.Selected Then
                'Here you will get all CheckBoxList Selected Items
                'You can do any operation as you like
                'For simplicity just printed the value
                Response.Write(oItem.Value + "|")
            End If
        Next

        GridView1.EditIndex = -1
        Bind_CheckBoxList()
    End Sub

    Protected Sub GridView1_RowCancelingEdit(sender As Object, e As System.Web.UI.WebControls.GridViewCancelEditEventArgs)
        GridView1.EditIndex = -1
        Bind_CheckBoxList()
    End Sub

Note: GridView1.EditIndex = -1 has special meaning. Remove the line & see the output.

Now run the example. Hope now you can control CheckBoxLixt within GridView in Edit Mode.

Download Code Example C#        Download Code Example VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code