Selecting Checkboxes inside the GridView Control using ASP.Net

HTML CODE: Just copy and paste the following code in your .ASPX page.

—————————————————————————————–
<body>
<form id=”form1″ runat=”server”>
<div>
<table width=”90%”>
<tr>
<td colspan=”4″>
<asp:GridView ID=”DataGV” runat=”server” AutoGenerateColumns=”False” CellPadding=”4″
GridLines=”Horizontal” BackColor=”White” BorderColor=”#336666″ BorderStyle=”Double”
BorderWidth=”3px” Font-Bold=”True” Font-Names=”Verdana” Font-Size=”X-Small” Height=”1px”
Width=”100%” AllowSorting=”True” HorizontalAlign=”Center” DataKeyNames=”EmployeeID”
AllowPaging=”True” PageSize=”50″>
<RowStyle BackColor=”White” ForeColor=”#333333″ />
<Columns>
<asp:TemplateField HeaderText=”Select”>
<ItemTemplate>
<asp:CheckBox ID=”CheckBox1″ runat=”server” />
<asp:Label ID=”LBLEmpID” runat=”server” Text='<%# container.dataitem(“EmployeeID”) %>’
Visible=”false”></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign=”Left” />
<FooterStyle HorizontalAlign=”Left” />
</asp:TemplateField>
<asp:TemplateField HeaderText=”Name” SortExpression=”LastName”>
<HeaderStyle HorizontalAlign=”Left” />
<ItemTemplate>
<asp:Label ID=”LblName” runat=”server” Text='<%# trim(Eval (“LastName”)) + “, ” + trim( Eval (“FirstName”))%>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField=”Title” HeaderText=”Title” SortExpression=”Title”>
<HeaderStyle HorizontalAlign=”Left” />
</asp:BoundField>
<asp:BoundField DataField=”City” HeaderText=”City” SortExpression=”City”>
<HeaderStyle HorizontalAlign=”Left” />
</asp:BoundField>
<asp:TemplateField HeaderText=”HireDate” SortExpression=”HireDate”>
<ItemStyle HorizontalAlign=”Right” />
<HeaderStyle HorizontalAlign=”Right” />
<ItemTemplate>
<asp:Label ID=”LblHireDate” runat=”server” Text='<%# Bind(“HireDate”, “{0:d}”) %>’></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor=”White” Font-Bold=”True” ForeColor=”Black” Font-Size=”Small”
VerticalAlign=”Top” />
<AlternatingRowStyle BackColor=”#D6E3F7″ />
<FooterStyle BackColor=”#009900″ Font-Bold=”True” ForeColor=”White” Font-Size=”Small”
HorizontalAlign=”Right” />
<PagerSettings PageButtonCount=”30″ Mode=”NumericFirstLast” NextPageText=”” PreviousPageText=””
Position=”TopAndBottom” />
<PagerStyle BackColor=”Silver” ForeColor=”White” HorizontalAlign=”Center” Font-Names=”Verdana”
Font-Size=”Small” />
</asp:GridView>
 
</td>
</tr>
<tr>
<td align=”center” colspan=”4″>
<asp:Button ID=”btnSubmit” runat=”server” Text=”Submit” Width=”129px” /></td>
</tr>
<tr>
<td colspan=”4″>
</td>
</tr>
</table>
</div>
</form>
</body>
—————————————————————————————–

CODE BEHIND: Just copy and paste the following code in your .ASPX.vb page.

‘Copy and paste the following code in your page_Load event:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
‘Dim objbllNews As New BLL.News
If (IsPostBack = False) Then
Dim dsNews As DataSet
Try
Dim dsData As DataSet = New DataSet()
Dim CMD As SqlCommand

‘Change the following connection string depends on your sql server ‘authentication
Dim con As SqlConnection = New SqlConnection(“Data Source=localhost;Initial Catalog=Northwind;TimeOut=60;User ID=sa;Password=;”)
CMD = New SqlCommand(“SELECT * FROM [Employees]”, con)

Dim adpt As New SqlDataAdapter(CMD)
adpt.Fill(dsData)

DataGV.DataSource = dsData
DataGV.DataBind()
Catch ex As Exception
Throw ex
End Try
End If
End Sub

‘Write the following code in your GridView’s RowDataBound event:

Protected Sub DataGV_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles DataGV.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then ‘1
Dim Chk As CheckBox = e.Row.FindControl(“CheckBox1”) ‘2
Page.ClientScript.RegisterStartupScript(Me.GetType(), “MyScript”, ” function HighlightSelected(colorcheckboxselected, RowState) { if (colorcheckboxselected.checked) colorcheckboxselected.parentElement.parentElement.style.backgroundColor=’#FFAA63′; else { if (RowState==’0′) colorcheckboxselected.parentElement.parentElement.style.backgroundColor=’white’; else colorcheckboxselected.parentElement.parentElement.style.backgroundColor=’#D6E3F7′; } }”, True) ‘3
Chk.Attributes.Add(“onclick”, “HighlightSelected(this,'” + Convert.ToString(e.Row.RowState) + “‘ );”) ‘4
End If ‘5
End Sub

‘Write the following code in your button’s click event

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
If IsPostBack = True Then
Dim str As StringBuilder = New StringBuilder()
‘ Select the checkboxes from the GridView control
Dim i As Integer
For i = 0 To DataGV.Rows.Count – 1 Step i + 1
Dim row As GridViewRow = DataGV.Rows(i)
Dim isChecked As Boolean = (CType(row.FindControl(“CheckBox1”), CheckBox)).Checked
If (isChecked) Then
str.Append(DataGV.Rows(i).Cells(2).Text)
End If
Next
‘ prints out the result
Response.Write(str.ToString())
End If
End Sub

Regards….

VIJAY MODI

any query Contact: vijaymodi_81@yahoo.com

Advertisements

About Vijay Modi

Having 12+ years of experience in web application development. Expertise in various domains like E-Commerce, E-Learning, Insurance. I have expertise in web application development, window application development, Performance improvement, bug fixing etc. I am believing in quality work and achieving deadlines. Also like to work on new technologies and quick learner.
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

11 Responses to Selecting Checkboxes inside the GridView Control using ASP.Net

  1. Jigar says:

    Great solution yaar.
    I never seen before like this sortcut solution.
    I tried to solve this problem since last 2 weeks but finally i got solution from your blog.
    vary vary thanks to You

  2. Pappu says:

    Thanks sir,
    finally I got Answer to use your articles.
    What ever you r but u just come like god for me because without your article help i cant complete my project in dedline.
    Thank Lot

  3. Pingback: Programming Tutorials

  4. harmeet says:

    Thanx

    VIJAY MODI

    This code is working well

    CODE BEHIND: Just copy and paste the following code in your .ASPX.vb page.

    ‘Copy and paste the following code in your page_Load event:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    ‘Dim objbllNews As New BLL.News
    If (IsPostBack = False) Then
    Dim dsNews As DataSet
    Try
    Dim dsData As DataSet = New DataSet()
    Dim CMD As SqlCommand

    ‘Change the following connection string depends on your sql server ‘authentication
    Dim con As SqlConnection = New SqlConnection(”Data Source=localhost;Initial Catalog=Northwind;TimeOut=60;User ID=sa;Password=;”)
    CMD = New SqlCommand(”SELECT * FROM [Employees]“, con)

    Dim adpt As New SqlDataAdapter(CMD)
    adpt.Fill(dsData)

    DataGV.DataSource = dsData
    DataGV.DataBind()
    Catch ex As Exception
    Throw ex
    End Try
    End If
    End Sub

    ‘Write the following code in your GridView’s RowDataBound event:

    Protected Sub DataGV_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles DataGV.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then ‘1
    Dim Chk As CheckBox = e.Row.FindControl(”CheckBox1″) ‘2
    Page.ClientScript.RegisterStartupScript(Me.GetType(), “MyScript”, ” function HighlightSelected(colorcheckboxselected, RowState) { if (colorcheckboxselected.checked) colorcheckboxselected.parentElement.parentElement.style.backgroundColor=’#FFAA63′; else { if (RowState==’0′) colorcheckboxselected.parentElement.parentElement.style.backgroundColor=’white’; else colorcheckboxselected.parentElement.parentElement.style.backgroundColor=’#D6E3F7′; } }”, True) ‘3
    Chk.Attributes.Add(”onclick”, “HighlightSelected(this,’” + Convert.ToString(e.Row.RowState) + “‘ );”) ‘4
    End If ‘5
    End Sub

    ‘Write the following code in your button’s click event

    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
    If IsPostBack = True Then
    Dim str As StringBuilder = New StringBuilder()
    ‘ Select the checkboxes from the GridView control
    Dim i As Integer
    For i = 0 To DataGV.Rows.Count – 1 Step i + 1
    Dim row As GridViewRow = DataGV.Rows(i)
    Dim isChecked As Boolean = (CType(row.FindControl(”CheckBox1″), CheckBox)).Checked
    If (isChecked) Then
    str.Append(DataGV.Rows(i).Cells(2).Text)
    End If
    Next
    ‘ prints out the result
    Response.Write(str.ToString())
    End If
    End Sub

  5. 6gThank’s for greate post.5b I compleatly disagree with last post . hsb
    купить ламинат 0u

  6. Phaneesh Gururaj says:

    In case you need to extract the same from a HyperLink Field, use the following code.

    StringBuilder str = new StringBuilder();
    HyperLink ipn = null;
    HyperLink ipin = null;
    for (int i = 0; i < gvwPlatSearchresults.Rows.Count; i++)
    {
    GridViewRow row = gvwPlatSearchresults.Rows[i];
    ipn = (HyperLink)row.Cells[2].Controls[0];
    ipin = (HyperLink)row.Cells[3].Controls[0];
    bool isChecked = ((CheckBox)row.FindControl(“chkRowLevel”)).Checked;

    if (isChecked)
    {
    str.Append(ipn.Text + “:” + ipin.Text);
    }
    }

  7. Vipin Sharma says:

    hello friends,
    i am loading a gridView in a postback based on selection made in DropdownList.
    Gridview contains checkbox that can be unchecked and saved all change at once….
    My problem is , once i submit the repost, i can not get was checked ..
    can anyone help please,
    Thanks.

  8. Vipin Sharma says:

    protected void Page_Load(object sender, EventArgs e)
    {

    if (!IsPostBack) {
    DropDownList1.DataSource = //……works
    DropDownList1.DataBind();
    }
    if (IsPostBack)
    {
    loaddata(Int32.Parse(DropDownList1.SelectedValue)); // works
    }

    }
    protected void ApplyChanges_Click(object sender, EventArgs e)
    {

    StringBuilder str = new StringBuilder();
    for (int i = 0; i < GridView1.Rows.Count-1; i++)
    { GridViewRow row = GridView1.Rows[i];
    bool isChecked = ((CheckBox)row.FindControl(“cbRows”)).Checked;
    if (isChecked) {
    str.Append(“a;”);—NEVER gets here
    }
    }
    Label2.Text= (“.” + str.ToString());
    }

  9. nikhil says:

    vijay , plz give this code in asp.net as i m workin on same.

  10. hope1567 says:

    Dim i, k As Integer
    Dim j As Integer = 0
    Dim q As Integer = 0
    Dim isChecked As Boolean
    Dim MoreThanOneTime As Boolean = False

    For i = 0 To FormGV.Rows.Count – 1
    isChecked = DirectCast(FormGV.Rows(i).FindControl(“CheckBox1”), CheckBox).Checked
    If isChecked Then
    j += 1
    End If
    Next

    Dim arrCpyNo As String() = New String(j – 1) {}
    Dim arrCpyName As String() = New String(j – 1) {}
    Dim arrDate As String() = New String(j – 1) {}

    For i = 0 To FormGV.Rows.Count – 1
    isChecked = DirectCast(FormGV.Rows(i).FindControl(“CheckBox1”), CheckBox).Checked
    If MoreThanOneTime Then
    q += 1
    End If

    For k = q To j – 1
    If isChecked Then
    arrCpyNo(k) = FormGV.Rows(i).Cells(1).Text
    arrCpyName(k) = FormGV.Rows(i).Cells(2).Text
    arrDate(k) = FormGV.Rows(i).Cells(3).Text
    MoreThanOneTime = True
    Exit For
    Else
    MoreThanOneTime = False
    End If
    Next
    Next

  11. Allen says:

    can you change the forecolor also besides the background color at the time?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s