How to see if a checkbox is checked in gridview?

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 1402 Views - Last Post: 22 January 2012 - 05:40 PM Rate Topic: -----

Topic Sponsor:

#1 Ecstatic  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 39
  • Joined: 20-March 11

How to see if a checkbox is checked in gridview?

Posted 19 January 2012 - 04:10 AM

I have a Gridview in which I have made a column of checkboxes named 'Status'. When the user clicks a button I want to see if a checkbox in particular row was checked by him or not. Code I have written is:
for (int i = 0; i <= Grid.Rows.Count; i++)
        {
            if (if checkbox is checked)
                d = m.Mark(Grid.Rows[i].Cells[1].Text, Date.Text, 'P');
            else
                d = m.Mark(Grid.Rows[i].Cells[1].Text, Date.Text, 'A');
        }


What code should I write in (if checkbox is checked) so that I can get the desired result?

Is This A Good Question/Topic? 0
  • +

Replies To: How to see if a checkbox is checked in gridview?

#2 hemantwithu  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 23
  • Joined: 18-October 11

Re: How to see if a checkbox is checked in gridview?

Posted 19 January 2012 - 04:30 AM

You need to get the Checkbox checked Row in the GridView using C#
void ActionSave() {
        object Chk;
        strong;
        ((GridViewRow)(D));
        string EmployeeID = "";
        foreach (D in GVTD.Rows) {
            Chk = D.FindControl("ChkSelect");
            if ((Chk.Checked == true)) {
                EmployeeID = D.Cell(1).Text.Trim();
            }
        }

}
Was This Post Helpful? 0
  • +
  • -

#3 Ecstatic  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 39
  • Joined: 20-March 11

Re: How to see if a checkbox is checked in gridview?

Posted 19 January 2012 - 08:37 AM

Can you please explain it a bit? I could not get what you meant
Was This Post Helpful? 0
  • +
  • -

#4 Frinavale  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 202
  • View blog
  • Posts: 775
  • Joined: 03-June 10

Re: How to see if a checkbox is checked in gridview?

Posted 19 January 2012 - 10:35 AM

What you need to do is loop through the GridViewRows.
Once you have a GridViewRow you need to use it's FindControl method to retrieve your CheckBox that is in the row. Once you have the CheckBox you can see if it's checked or not using it's Checked property.
CheckBox statusCheckBox;
GridViewRow currentRow;

for (int i = 0; i <= Grid.Rows.Count; i++)
{
  currentRow = Grid.Rows[i];
  statusCheckBox = currentRow.FindControl("Status");

  if (statusCheckBox.Checked)
  {              d = m.Mark(currentRow.Cells[1].Text, Date.Text, 'P');}
  else
  {              d = m.Mark(currentRow.Cells[1].Text, Date.Text, 'A');}
}

This post has been edited by Frinavale: 19 January 2012 - 10:36 AM

Was This Post Helpful? 1
  • +
  • -

#5 Ecstatic  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 39
  • Joined: 20-March 11

Re: How to see if a checkbox is checked in gridview?

Posted 19 January 2012 - 11:44 AM

View PostFrinavale, on 19 January 2012 - 10:35 AM, said:

What you need to do is loop through the GridViewRows.
Once you have a GridViewRow you need to use it's FindControl method to retrieve your CheckBox that is in the row. Once you have the CheckBox you can see if it's checked or not using it's Checked property.
CheckBox statusCheckBox;
GridViewRow currentRow;

for (int i = 0; i <= Grid.Rows.Count; i++)
{
  currentRow = Grid.Rows[i];
  statusCheckBox = currentRow.FindControl("Status");

  if (statusCheckBox.Checked)
  {              d = m.Mark(currentRow.Cells[1].Text, Date.Text, 'P');}
  else
  {              d = m.Mark(currentRow.Cells[1].Text, Date.Text, 'A');}
}


I tried this but it is giving me an error "Object reference not set to an instance of an object" at line 09. WHat could be the reason for this?
Was This Post Helpful? 0
  • +
  • -

#6 Ecstatic  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 39
  • Joined: 20-March 11

Re: How to see if a checkbox is checked in gridview?

Posted 19 January 2012 - 11:52 AM

I also tried this code:
CheckBox chkUpdate = ((CheckBox)Grid.Rows[0].FindControl("Status"));

And it always stores 'null' in the chkupdate. Why is that so?
Was This Post Helpful? 0
  • +
  • -

#7 Frinavale  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 202
  • View blog
  • Posts: 775
  • Joined: 03-June 10

Re: How to see if a checkbox is checked in gridview?

Posted 19 January 2012 - 11:53 AM

Is the "ID" property of the check box in the the template actually named "Status"?
Or is that ID something else?
Did you forget to give an ID to the check box?

The FindControl method returns null/nothing if it is unable to retrieve a control with the ID provided.

-Frinny
Was This Post Helpful? 1
  • +
  • -

#8 Ecstatic  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 39
  • Joined: 20-March 11

Re: How to see if a checkbox is checked in gridview?

Posted 19 January 2012 - 12:01 PM

Yes the ID is Status. Even then it is returning null. I wonder if it is even storing the status of checkbox...?
Was This Post Helpful? 0
  • +
  • -

#9 Frinavale  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 202
  • View blog
  • Posts: 775
  • Joined: 03-June 10

Re: How to see if a checkbox is checked in gridview?

Posted 19 January 2012 - 12:05 PM

It's not the "status" of the check box that it's trying to retrieve.
It's trying to retrieve the check box.

If your CheckBox is declared within an Edit template then you would have to do this in your edit code.

If your CheckBox is not within your edit template then you can loop through every row as you are doing.

It would help if you posted your ASP.NET TemplateField code that contains the CheckBox.
Was This Post Helpful? 1
  • +
  • -

#10 Ecstatic  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 39
  • Joined: 20-March 11

Re: How to see if a checkbox is checked in gridview?

Posted 19 January 2012 - 01:06 PM

Here is asp.net code
<asp:TemplateField AccessibleHeaderText="Status" HeaderText="Status" 
                               ConvertEmptyStringToNull="False">
                               <EditItemTemplate>
                                   <asp:CheckBox ID="Status" runat="server"/>
                               </EditItemTemplate>
                               <ItemTemplate>
                                   <asp:CheckBox ID="Status" runat="server"/>
                               </ItemTemplate>
                           </asp:TemplateField>



Edit: Posted the wrong code earlier.

This post has been edited by Ecstatic: 19 January 2012 - 01:11 PM

Was This Post Helpful? 0
  • +
  • -

#11 Frinavale  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 202
  • View blog
  • Posts: 775
  • Joined: 03-June 10

Re: How to see if a checkbox is checked in gridview?

Posted 19 January 2012 - 01:57 PM

I don't know what you're doing wrong so I created a working web page that you can use as an example.

I added an aspx page to a web application.
This page is named "WebForm1.aspx".
It has C# code as it's code behind.

Here is the html/asp markup for the page:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="Grid" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField AccessibleHeaderText="Status" HeaderText="Status" ConvertEmptyStringToNull="False">
                    <EditItemTemplate>
                        <asp:CheckBox ID="Status" runat="server" />
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="Status" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField HeaderText="Name" DataField="Name" />
            </Columns>
        </asp:GridView>
        <div>

            <asp:Button ID="doIt" runat="server" Text="Show Selected Items" onclick="doIt_Click" />
            <br />
            <p> The checked indices were:</p>
            <asp:Label ID="checkedItems" runat="server" />
        </div>
    </div>
    </form>
</body>
</html>


Here is the C# code behind for the page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        private System.Data.DataTable dataSource;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["dataSource"] == null)
            {
                dataSource = CreateDataSource();
                Session["dataSource"] = dataSource;
            }
            else
            {
                dataSource = (System.Data.DataTable)Session["dataSource"];
            }

        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            Grid.DataSource = dataSource;
            Grid.DataBind();
        }

        protected void doIt_Click(object sender, EventArgs e)
        {
            System.Text.StringBuilder str = new System.Text.StringBuilder();
            CheckBox statusCheckBox;
            GridViewRow currentRow;
           
            for (int i = 0; i <= Grid.Rows.Count-1; i++)
            {
                currentRow = Grid.Rows[i];
                statusCheckBox = (CheckBox)currentRow.FindControl("Status");

                if (statusCheckBox.Checked)
                {
                    if (str.Length > 0)
                    {
                        str.Append(", ");
                    }
                    str.Append(i.ToString());

                }
            }
            checkedItems.Text = str.ToString();
        }


        private System.Data.DataTable CreateDataSource()
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("Name");
            for (int i = 0; i < 10; i++)
            {
                System.Data.DataRow dr = dt.NewRow();
                dr[0] = String.Format("{0}{1}", "Name", i.ToString());
                dt.Rows.Add(dr);
            }
            return dt;
        }
    }
}

This post has been edited by Frinavale: 20 January 2012 - 10:51 AM

Was This Post Helpful? 1
  • +
  • -

#12 Nakor  Icon User is offline

  • ASP.NET/C# Developer
  • member icon

Reputation: 346
  • View blog
  • Posts: 1,228
  • Joined: 28-April 09

Re: How to see if a checkbox is checked in gridview?

Posted 19 January 2012 - 03:58 PM

Something else to think about.

When the grid loads does it load with all checkboxes checked/unchecked? If not then how are you going to determine which of the checkboxes were checked by the user and weren't loaded already checked?

Anyway, on to the main question. If I were wanting to access each row to determine if it had a checkbox that was checked or not I would do so in the following manner:

            foreach (GridViewRow row in Grid.Rows)
            {
                // Only look at the data rows
                if (row.RowType == DataControlRowType.DataRow)
                {
                    Control ctrl = row.FindControl("ControlID");
 
                    // Verify control is found and that it is a checkbox
                    if (ctrl != null && ctrl is CheckBox)
                    {
                        CheckBox cb = ctrl as CheckBox;

                        if (cb.Checked)
                        {
                          // rest of code
                        }
                    }
                    else
                    {
                        // Code to handle checkbox not being found
                    }
                }
            }



You may need to alter control names and such to get it to work, but it should give you a start.

This post has been edited by Nakor: 19 January 2012 - 03:59 PM

Was This Post Helpful? 0
  • +
  • -

#13 Ecstatic  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 39
  • Joined: 20-March 11

Re: How to see if a checkbox is checked in gridview?

Posted 19 January 2012 - 09:57 PM

Frinavale
Thank You so much for your big help. I tried your page and it works fine. But I am still unable to figure out what is wrong with my code. I am not using PreRender function. Could it be the reason? How can i use it when my data source is a database?

Nakor
I am quite new to asp.net so I don't understand it very much. However this is asp.net code I have:

<%@ Page Title="Mark Attendance" Language="C#" MasterPageFile="~/AMS.master" AutoEventWireup="true" CodeFile="MarkAttendance.aspx.cs" Inherits="MarkAttendance" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
    </asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<center>
    <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" 
        EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal">
        <Items>
            <asp:MenuItem NavigateUrl="~/Home.aspx" Text="Home" />
            <asp:MenuItem NavigateUrl="~/AddStudent.aspx" Text="Add Student" />
            <asp:MenuItem NavigateUrl="~/ReviewClass.aspx" Text="Review Class" />
            <asp:MenuItem NavigateUrl="~/MarkAttendance.aspx" Text="Mark Attendance" />
            <asp:MenuItem NavigateUrl="~/ReviewAttendance.aspx" Text="Review Attendance" />
            <asp:MenuItem NavigateUrl="~/ModifyAttendance.aspx" Text="Modify Attendance" />
            <asp:MenuItem NavigateUrl="~/ModifyStudent.aspx" Text="Modify Student" />
            <asp:MenuItem NavigateUrl="~/DeleteStudent.aspx" Text="Delete Student" />
        </Items>
    </asp:Menu>

                 

    <p style="color: #000000; empty-cells: show; table-layout: auto">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
                   Date :&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="Date" runat="server" ReadOnly="True" Width="80px"></asp:TextBox>
    </p>
    <p style="color: #000000; empty-cells: show; table-layout: auto">
                   Students:
                   <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </p>
    <p style="color: #000000; empty-cells: show; table-layout: auto">
                   &nbsp;<asp:GridView ID="Grid" runat="server" CellPadding="4" CellSpacing="4" 
                       ForeColor="#333333" GridLines="None" style="margin-left: 0px">
                       <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                       <Columns>
                           <asp:TemplateField AccessibleHeaderText="Status" HeaderText="Status" 
                               ConvertEmptyStringToNull="False">
                               <EditItemTemplate>
                                   <asp:CheckBox ID="Status" runat="server" checked = "false"/>
                               </EditItemTemplate>
                               <ItemTemplate>
                                   <asp:CheckBox ID="Status" runat="server" checked = "false"/>
                               </ItemTemplate>
                           </asp:TemplateField>
                       </Columns>
                       <EditRowStyle BackColor="#999999" />
                       <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                       <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                       <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                       <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                       <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                       <SortedAscendingCellStyle BackColor="#E9E7E2" />
                       <SortedAscendingHeaderStyle BackColor="#506C8C" />
                       <SortedDescendingCellStyle BackColor="#FFFDF8" />
                       <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                   </asp:GridView>
    </p>
    <p style="color: #000000; empty-cells: show; table-layout: auto">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                   <asp:Button ID="Update" runat="server" onclick="Update_Click" Text="Update" />
    </p>
    <p style="color: #000000; empty-cells: show; table-layout: auto">
                   &nbsp;&nbsp;
    </p>
                   
                <p style="color: #000000; empty-cells: show; table-layout: auto">
                    &nbsp;</p></center>
    <p>
        &nbsp;</p>
    <p>
        &nbsp;</p>
</asp:Content>





And this is the C# code behind it:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MarkAttendance : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Date.Text = DateTime.Now.ToString("d-M-yyyy");
        mainprog d = new mainprog();
        DataSet ds = null;
        ds = d.reviewClass();
        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
        {
            Grid.DataSource = ds.Tables[0];
            Grid.DataBind();
        }
    }
    protected void Update_Click(object sender, EventArgs e)
    {
        CheckBox chkUpdate = ((CheckBox)Grid.Rows[0].FindControl("Status")); //Just checking first row as a test
        if (chkUpdate.Checked)
            Label1.Text = "True";
        else
            Label1.Text = "False";
    }
}

This post has been edited by Ecstatic: 19 January 2012 - 09:57 PM

Was This Post Helpful? 0
  • +
  • -

#14 Frinavale  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 202
  • View blog
  • Posts: 775
  • Joined: 03-June 10

Re: How to see if a checkbox is checked in gridview?

Posted 20 January 2012 - 10:48 AM

Yes that is your problem.

Bind your GridView to your data source at the last possible point in the Page's life cycle.
If you bind it in the page load, then you will over write the data that the user provided with the previous data (by binding to old data).

You are currently binding your GridView in the beginning of the Page life cycle: the Page Load event. At this point the user's provided values are over written...so by the time your Button Click event is occurring (after the page load) there's nothing there!

There are examples out there that will bind the GridView in various places but you just need to do it once...at the end of the page life cycle.

:)

So move your binding code out of the page load and into the page prerender event :)

-Frinny
Was This Post Helpful? 1
  • +
  • -

#15 Frinavale  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 202
  • View blog
  • Posts: 775
  • Joined: 03-June 10

Re: How to see if a checkbox is checked in gridview?

Posted 20 January 2012 - 11:49 AM

I took your posted code and modified it to work properly.

Here's my WebForm1 that contains your grid.
You'll notice that I added a template field column for the student's name that has a Label in it for displaying the student's name. I use that to select the row from the DataSet when I want to update if the student is "in attendance".

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p style="color: #000000; empty-cells: show; table-layout: auto">
            Date :
            <asp:TextBox ID="Date" runat="server" ReadOnly="True" Width="80px"></asp:TextBox>
        </p>
        <p style="color: #000000; empty-cells: show; table-layout: auto">
            Students:
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </p>
        <p style="color: #000000; empty-cells: show; table-layout: auto">
            <asp:GridView ID="Grid" runat="server" AutoGenerateColumns="false" CellPadding="4"
                CellSpacing="4" ForeColor="#333333" GridLines="None" Style="margin-left: 0px">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <Columns>
                    <asp:TemplateField AccessibleHeaderText="Status" HeaderText="Flip Attendance" ConvertEmptyStringToNull="False">
                        <ItemTemplate>
                            <asp:CheckBox ID="Status" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField AccessibleHeaderText="Name" HeaderText="Student Name" ConvertEmptyStringToNull="False">
                        <ItemTemplate>
                            <asp:Label ID="StudentName" runat="server" Text="<%# Bind('Name') %>" />
                        </ItemTemplate>
                    </asp:TemplateField>
                     <asp:TemplateField AccessibleHeaderText="Is In Attenance" HeaderText="Is In Attenance" ConvertEmptyStringToNull="False">
                        <ItemTemplate>
                             <asp:Label ID="IsInAttendance" runat="server" Text="<%# Bind('IsInAttendance') %>" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <EditRowStyle BackColor="#999999" />
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            </asp:GridView>
        </p>
        <p style="color: #000000; empty-cells: show; table-layout: auto">
            <asp:Button ID="Update" runat="server" onclick="Update_Click" Text="Update" />
        </p>
    </div>
    </form>
</body>
</html>




Here's my C# code.
I added a "mainprog" class that has a reviewClass method that returns a DataSet like your code.

When you click the button I:

  • Loop through each row in the GridView
    • Grab the CheckBox which is part of the GridViewRow
    • If the CheckBox is checked
      • I retrieve the row in the DataTable (that's part of the DataSet) which the GridViewRow is displaying based on the Student's name
      • I begin editing the row
      • I flip the "IsInAttendance" column (if it was true, I change it to false...if it was false, I change it to true)
      • I end editing the row

  • I save the data set back into session (you would commit the changes to your database)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {

        private DataSet ds = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            Date.Text = DateTime.Now.ToString("d-M-yyyy");
            if (Session["ds"] == null)
            {
                mainprog d = new mainprog();
                ds = d.reviewClass();
                Session["ds"] = ds;
            }
            else
            {
                ds = (DataSet)Session["ds"];
            }

        }

        void Page_PreRender(object sender, EventArgs e)
        {
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                Grid.DataSource = ds.Tables[0];
                Grid.DataBind();
            }
        }
        protected void Update_Click(object sender, EventArgs e)
        {

            CheckBox chkUpdate;
            GridViewRow currentRow;
            Label lblName;

            for (int i = 0; i <= Grid.Rows.Count - 1; i++)
            {
                currentRow = Grid.Rows[i];
                chkUpdate = (CheckBox)currentRow.FindControl("Status");
                if (chkUpdate.Checked)
                {

                    lblName = (Label)currentRow.FindControl("StudentName");
                    string studentName = lblName.Text;
                    string expression;
                    expression = "Name=" + "'" + studentName + "'";
                    DataRow[] rowsEffected = ds.Tables[0].Select(expression);
                    foreach (DataRow dr in rowsEffected)
                    {
                        dr.BeginEdit();
                        dr["IsInAttendance"] = !((bool)dr["IsInAttendance"]);
                        dr.EndEdit();
                    }
                }
            }
            Session["ds"] = ds;
        }
    }

    public class mainprog
    {

        public mainprog()
        {

        }
        public DataSet reviewClass()
        {
            DataSet ds = new DataSet();

            System.Data.DataTable dt = new System.Data.DataTable();
            dt.TableName = "Students";
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("IsInAttendance", typeof(bool));
            for (int i = 0; i < 10; i++)
            {
                System.Data.DataRow dr = dt.NewRow();
                dr["Name"] = String.Format("{0}{1}", "Name", i.ToString());
                dr["IsInAttendance"] = false;
                dt.Rows.Add(dr);
            }
            ds.Tables.Add(dt);
            return ds;
        }
    }

}

This post has been edited by Frinavale: 20 January 2012 - 02:33 PM

Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2