Wednesday, August 14, 2013

How to use Checkbox control inside Gridview in asp.net

Introduction: In this article I will explain how we can use the checkbox control inside the Gridview in Asp.net.

I have a Gridview binded to database and show detail of Register user who are not authorized by admin yet. Here I give the option to select/Unselect all unauthorized user from header checkbox or single-2 checkbox selection.
I have a Create a Table USER_REGISTRATION:
Id
int
Username
varchar(50)
Name
varchar(50)
Email
varchar(50)
Gender
varchar(50)
Is_autho
bit

Id is primary key and autoincrement.
Add a new webform to project. Drag and drop the controls from Toolbox and desgined .aspx page as mention below:
<table align="center"><tr><td>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataKeyNames="Id,Username" onrowdatabound="GridView1_RowDataBound">
            <Columns>
            <asp:TemplateField HeaderText="CheckAll">
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" onclick="javascript:SelectheaderCheckboxes(this)"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkselect" runat="server"
              AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
                <asp:TemplateField HeaderText="Username">
                    <ItemTemplate>
                        <asp:Label ID="lblusername" runat="server" Text='<%# Eval("Username") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                       <asp:Label ID="lblname" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Email">
                    <ItemTemplate>
                        <asp:Label ID="lblemail" runat="server" Text='<%# Eval("Email") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Gender">
                    <ItemTemplate>
                        <asp:Label ID="lblsex" runat="server" Text='<%# Eval("Gender") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
             
            </Columns>
        </asp:GridView></td></tr>
        <tr><td> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Authorize User" /></td></tr>
       </table>

Put the below given Javascript in between Head tag of .aspx page:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
    function SelectheaderCheckboxes(headerchk) {
        debugger
        var gvdetail = document.getElementById('GridView1');
        var i;
        if (headerchk.checked) {
            for (i = 0; i < gvdetail.rows.length; i++) {
                var inputs = gvdetail.rows[i].getElementsByTagName('input');
                inputs[0].checked = true;
            }
        }
        else {
            for (i = 0; i < gvdetail.rows.length; i++) {
                var inputs = gvdetail.rows[i].getElementsByTagName('input');
                inputs[0].checked = false;
            }
        }
    }
    function Selectchildcheckboxes(header) {
        var ck = header;
        var count = 0;
        var gvdetail = document.getElementById('GridView1');
        var headerchk = document.getElementById(header);
        var rowcount = gvdetail.rows.length;
        for (i = 1; i < gvdetail.rows.length; i++) {
            var inputs = gvdetail.rows[i].getElementsByTagName('input');
            if (inputs[0].checked) {
                count++;
            }
        }
        if (count == rowcount - 1) {
            headerchk.checked = true;
        }
        else {
            headerchk.checked = false;
        }
    }
</script>



Note: Don’t forget to add ConnectionString in web.config file:
<connectionStrings>
      <add name="Connection" connectionString="Data Source=VIJAY-PC;Initial Catalog=TEST_APPLICATION;Integrated Security=True"/>
    </connectionStrings>

Now on .aspx.cs page write the below given code to bind gridview:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString.ToString());
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bindgrid();
        }
    }
    private void Bindgrid()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from USER_REGISTRATION where Is_autho = 0", con);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        else
        {
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            GridView1.DataSource = ds;
            GridView1.DataBind();
            int columncount = GridView1.Rows[0].Cells.Count;
            GridView1.Rows[0].Cells.Clear();
            GridView1.Rows[0].Cells.Add(new TableCell());
            GridView1.Rows[0].Cells[0].ColumnSpan = columncount;
            GridView1.Rows[0].Cells[0].Text = " NO record Found";
        }
        con.Close();
    }

In VB (.aspx.vb)
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Bindgrid()
        End If
    End Sub
    Private Sub Bindgrid()
        con.Open()
        Dim cmd As New SqlCommand("select * from USER_REGISTRATION where Is_autho = 0", con)
        Dim adp As New SqlDataAdapter(cmd)
        Dim ds As New DataSet()
        adp.Fill(ds)
        If ds.Tables(0).Rows.Count > 0 Then
            GridView1.DataSource = ds
            GridView1.DataBind()
        Else
            ds.Tables(0).Rows.Add(ds.Tables(0).NewRow())
            GridView1.DataSource = ds
            GridView1.DataBind()
            Dim columncount As Integer = GridView1.Rows(0).Cells.Count
            GridView1.Rows(0).Cells.Clear()
            GridView1.Rows(0).Cells.Add(New TableCell())
            GridView1.Rows(0).Cells(0).ColumnSpan = columncount
            GridView1.Rows(0).Cells(0).Text = " NO record Found"
        End If
        con.Close()
    End Sub

On Gridview RowDataBound write the below given code (.aspx.cs):
      protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                CheckBox chkselectall = (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
                CheckBox chk = (CheckBox)e.Row.FindControl("chkselect");
                chk.Attributes.Add("onclick", "javascript:Selectchildcheckboxes('" + chkselectall.ClientID + "')");
            }
        }

In VB (.aspx.vb)

Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim chkselectall As CheckBox = DirectCast(GridView1.HeaderRow.FindControl("chkSelectAll"), CheckBox)
            Dim chk As CheckBox = DirectCast(e.Row.FindControl("chkselect"), CheckBox)
            chk.Attributes.Add("onclick", "javascript:Selectchildcheckboxes('" + chkselectall.ClientID & "')")
        End If
    End Sub

After that on button click right the code (.aspx.cs):

protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                CheckBox chk = (CheckBox)row.FindControl("chkSelect");
                if (chk.Checked)
                {
                    int Id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
                    string username = GridView1.DataKeys[row.RowIndex].Values["Username"].ToString();
                    Messagebox("User " + username + " Authorized");
                    con.Open();
                    {
                        string sql = "update USER_REGISTRATION set Is_autho = 1 where Id = " + @Id;
                        using (SqlCommand cmd = new SqlCommand(sql, con))
                        {
                            cmd.Parameters.AddWithValue("@Id", Id);

                            cmd.ExecuteNonQuery();
                            con.Close();
                        }
                    }
                }
            }
            this.Bindgrid();
        }
        catch (Exception ex)
        {

        }
    }

//show message
    private void Messagebox(string Message)
    {
        Label lblMessageBox = new Label();

        lblMessageBox.Text =
            "<script language='javascript'>" + Environment.NewLine +
            "window.alert('" + Message + "')</script>";

        Page.Controls.Add(lblMessageBox);

    }

In VB (.aspx.vb)

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            For Each row As GridViewRow In GridView1.Rows
                Dim chk As CheckBox = DirectCast(row.FindControl("chkSelect"), CheckBox)
                If chk.Checked Then
                    Dim Id As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)
                    Dim username As String = GridView1.DataKeys(row.RowIndex).Values("Username").ToString()
                    Messagebox("User " & username & " Authorized")
                    con.Open()
                    If True Then
                        Dim sql As String = "update USER_REGISTRATION set Is_autho = 1 where Id = " & Id
                        Using cmd As New SqlCommand(sql, con)
                            cmd.Parameters.AddWithValue("@Id", Id)

                            cmd.ExecuteNonQuery()
                            con.Close()
                        End Using
                    End If
                End If
            Next
            Me.Bindgrid()

        Catch ex As Exception
        End Try
    End Sub

Private Sub Messagebox(Message As String)
        Dim lblMessageBox As New Label()

        lblMessageBox.Text = "<script language='javascript'>" + Environment.NewLine & "window.alert('" & Message & "')</script>"

        Page.Controls.Add(lblMessageBox)

    End Sub

Now run the project and check the result.

3 comments: