troubleshooting Question

working with a CheckBox in a DataGrid in WebForms

Avatar of maqskywalker
maqskywalker asked on
ASP.NETVisual Basic.NETSQL
2 Comments1 Solution97 ViewsLast Modified:
I'm using VB and ASP.NET Web Forms.

On my page i'm binding a DataGrid to a Sql Server Stored procedure.

Yest, I know GridView is the newer ASP.NET grid.
This is a model based on a old legacy web application.
That's why I need to use DataGrid.

The sql server table I'm using is a copy of the Employees table from the Northwind database.

This is the script to create the table:

USE [Northwind]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[NWEmployees](
	[EmployeeID] [int] NOT NULL,
	[LastName] [nvarchar](20) NOT NULL,
	[FirstName] [nvarchar](10) NOT NULL,
	[Title] [nvarchar](30) NULL,
	[TitleOfCourtesy] [nvarchar](25) NULL,
	[BirthDate] [datetime] NULL,
	[HireDate] [datetime] NULL,
	[Address] [nvarchar](60) NULL,
	[City] [nvarchar](15) NULL,
	[Region] [nvarchar](15) NULL,
	[PostalCode] [int] NULL,
	[Country] [nvarchar](15) NULL,
 CONSTRAINT [PK_Employees_NWEmployees] PRIMARY KEY CLUSTERED 
(
	[EmployeeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
INSERT [dbo].[NWEmployees] ([EmployeeID], [LastName], [FirstName], [Title], [TitleOfCourtesy], [BirthDate], [HireDate], [Address], [City], [Region], [PostalCode], [Country]) VALUES (1, N'Davolio', N'Nancy', N'Sales Representative', N'Ms.', CAST(N'1948-12-08T00:00:00.000' AS DateTime), CAST(N'1992-05-01T00:00:00.000' AS DateTime), N'507 - 20th Ave. E.
Apt. 2A', N'Seattle', N'WA', 98122, N'USA')
INSERT [dbo].[NWEmployees] ([EmployeeID], [LastName], [FirstName], [Title], [TitleOfCourtesy], [BirthDate], [HireDate], [Address], [City], [Region], [PostalCode], [Country]) VALUES (2, N'Fuller', N'Andrew', N'Vice President, Sales', N'Dr.', CAST(N'1952-02-19T00:00:00.000' AS DateTime), CAST(N'1992-08-14T00:00:00.000' AS DateTime), N'908 W. Capital Way', N'Tacoma', N'WA', 98401, N'USA')
INSERT [dbo].[NWEmployees] ([EmployeeID], [LastName], [FirstName], [Title], [TitleOfCourtesy], [BirthDate], [HireDate], [Address], [City], [Region], [PostalCode], [Country]) VALUES (3, N'Leverling', N'Janet', N'Sales Representative', N'Ms.', CAST(N'1963-08-30T00:00:00.000' AS DateTime), CAST(N'1992-04-01T00:00:00.000' AS DateTime), N'722 Moss Bay Blvd.', N'Kirkland', N'WA', 98033, N'USA')
INSERT [dbo].[NWEmployees] ([EmployeeID], [LastName], [FirstName], [Title], [TitleOfCourtesy], [BirthDate], [HireDate], [Address], [City], [Region], [PostalCode], [Country]) VALUES (4, N'Peacock', N'Margaret', N'Sales Representative', N'Mrs.', CAST(N'1937-09-19T00:00:00.000' AS DateTime), CAST(N'1993-05-03T00:00:00.000' AS DateTime), N'4110 Old Redmond Rd.', N'Redmond', N'WA', 98052, N'USA')
INSERT [dbo].[NWEmployees] ([EmployeeID], [LastName], [FirstName], [Title], [TitleOfCourtesy], [BirthDate], [HireDate], [Address], [City], [Region], [PostalCode], [Country]) VALUES (5, N'Buchanan', N'Steven', N'Sales Manager', N'Mr.', CAST(N'1955-03-04T00:00:00.000' AS DateTime), CAST(N'1993-10-17T00:00:00.000' AS DateTime), N'14 Garrett Hill', N'London', NULL, 95624, N'UK')
INSERT [dbo].[NWEmployees] ([EmployeeID], [LastName], [FirstName], [Title], [TitleOfCourtesy], [BirthDate], [HireDate], [Address], [City], [Region], [PostalCode], [Country]) VALUES (6, N'Suyama', N'Michael', N'Sales Representative', N'Mr.', CAST(N'1963-07-02T00:00:00.000' AS DateTime), CAST(N'1993-10-17T00:00:00.000' AS DateTime), N'Coventry House
Miner Rd.', N'London', NULL, 93722, N'UK')
INSERT [dbo].[NWEmployees] ([EmployeeID], [LastName], [FirstName], [Title], [TitleOfCourtesy], [BirthDate], [HireDate], [Address], [City], [Region], [PostalCode], [Country]) VALUES (7, N'King', N'Robert', N'Sales Representative', N'Mr.', CAST(N'1960-05-29T00:00:00.000' AS DateTime), CAST(N'1994-01-02T00:00:00.000' AS DateTime), N'Edgeham Hollow
Winchester Way', N'London', NULL, 45648, N'UK')
INSERT [dbo].[NWEmployees] ([EmployeeID], [LastName], [FirstName], [Title], [TitleOfCourtesy], [BirthDate], [HireDate], [Address], [City], [Region], [PostalCode], [Country]) VALUES (8, N'Callahan', N'Laura', N'Inside Sales Coordinator', N'Ms.', CAST(N'1958-01-09T00:00:00.000' AS DateTime), CAST(N'1994-03-05T00:00:00.000' AS DateTime), N'4726 - 11th Ave. N.E.', N'Seattle', N'WA', 98105, N'USA')
INSERT [dbo].[NWEmployees] ([EmployeeID], [LastName], [FirstName], [Title], [TitleOfCourtesy], [BirthDate], [HireDate], [Address], [City], [Region], [PostalCode], [Country]) VALUES (9, N'Dodsworth', N'Anne', N'Sales Representative', N'Ms.', CAST(N'1966-01-27T00:00:00.000' AS DateTime), CAST(N'1994-11-15T00:00:00.000' AS DateTime), N'7 Houndstooth Rd.', N'London', NULL, 98751, N'UK')
INSERT [dbo].[NWEmployees] ([EmployeeID], [LastName], [FirstName], [Title], [TitleOfCourtesy], [BirthDate], [HireDate], [Address], [City], [Region], [PostalCode], [Country]) VALUES (10, N'Duck', N'Daffy', N'Actor', NULL, NULL, NULL, NULL, NULL, NULL, 90210, NULL)
INSERT [dbo].[NWEmployees] ([EmployeeID], [LastName], [FirstName], [Title], [TitleOfCourtesy], [BirthDate], [HireDate], [Address], [City], [Region], [PostalCode], [Country]) VALUES (11, N'Duck', N'Donald', N'Disney Actor', NULL, NULL, NULL, NULL, NULL, NULL, 90211, NULL)

This is the script for the stored procedure:

USE [Northwind]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[NWEmployees_Get]
AS

SELECT [EmployeeID]
      ,[LastName]
      ,[FirstName]
      ,[Title]
      ,[BirthDate]
      ,[HireDate]
      ,[Address]
      ,[City]
      ,[Region]
      ,[PostalCode]
      ,[Country]
FROM [Northwind].[dbo].[NWEmployees]


GO


When I run my page it runs fine it looks like this:

Notice I have 2 buttons above the DataGrid.

If I click the Check Header CheckBox button I want the check box in the header row of the DataGrid that I circled in blue to get checked.
If I click the Uncheck Header CheckBox button I want the check box in the header row of the DataGrid that I circled in blue to get unchecked.

Screenshot.PNG
In the Button click event of Button1 i have this:

DataGridEmployees_SelectAll.Checked = True

But I noticed the vb is not recognizing the CheckBox in the DataGrid's header and I get this message.

Code.PNG
This is my code for my page.

Sample1.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Sample1.aspx.vb" Inherits="Sample1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .DGHeaderText {
            font-family: Arial;
            font-size: 12px;
            color: #000000;
            font-weight: bold;
        }

        .DGBodyText {
            font-family: Arial;
            font-size: 12px;
            color: #000000;
            font-weight: normal;
        }
    </style>
    <script type="text/javascript">
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Check DataGrid Header CheckBox</td>
                    <td><asp:Button ID="Button1" runat="server" Text="Check Header CheckBox" /></td>                    
                </tr>
                <tr>
                    <td>Uncheck DataGrid Header CheckBox</td>
                    <td><asp:Button ID="Button2" runat="server" Text="Uncheck Header CheckBox" /></td>                    
                </tr>
            </table>
        </div>
        <div id="DivEmployees">
            <asp:DataGrid ID="DataGridEmployees" runat="server" AutoGenerateColumns="False" Font-Size="8pt" CellPadding="3" BorderColor="Black" Width="400px" CssClass="DGHeaderText">
                <Columns>
                    <asp:TemplateColumn HeaderText="EmployeeID">
                        <ItemTemplate>
                            <asp:Label ID="EmployeeID" CssClass="DGBodyText" Text='<%# DataBinder.Eval(Container.DataItem, "EmployeeID") %>' runat="server" />
                        </ItemTemplate>
                        <ItemStyle HorizontalAlign="Center" />
                    </asp:TemplateColumn>
                    <asp:TemplateColumn HeaderText="contract">
                        <HeaderTemplate>
                            <asp:CheckBox runat="server" ID="DataGridEmployees_SelectAll" autopostback="true" OnCheckedChanged="DataGridEmployees_SelectAll_Click" />
                            <%--<asp:CheckBox runat="server" ID="DataGridEmployees_SelectAll" autopostback="true" OnCheckedChanged="DataGridEmployees_SelectAll_Click"  ClientIDMode="Static" />--%>
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:CheckBox ID="EmpId" runat="server" AutoPostBack="true" OnCheckedChanged="ChckedChanged" />
                        </ItemTemplate>
                    </asp:TemplateColumn>
                    <asp:TemplateColumn HeaderText="FirstName">
                        <ItemTemplate>
                            <asp:Label ID="FirstName" CssClass="DGBodyText" Text='<%# DataBinder.Eval(Container.DataItem, "FirstName") %>' runat="server" />
                        </ItemTemplate>
                    </asp:TemplateColumn>
                    <asp:TemplateColumn HeaderText="LastName">
                        <ItemTemplate>
                            <asp:Label ID="LastName" CssClass="DGBodyText" Text='<%# DataBinder.Eval(Container.DataItem, "LastName") %>' runat="server" />
                        </ItemTemplate>
                    </asp:TemplateColumn>
                    <asp:TemplateColumn HeaderText="Title">
                        <ItemTemplate>
                            <asp:Label ID="Title" CssClass="DGBodyText" Text='<%# DataBinder.Eval(Container.DataItem, "Title") %>' runat="server" />
                        </ItemTemplate>
                        <ItemStyle Wrap="False" />
                    </asp:TemplateColumn>
                    <asp:TemplateColumn HeaderText="PostalCode">
                        <ItemTemplate>
                            <asp:Label ID="PostalCode" CssClass="DGBodyText" Text='<%# DataBinder.Eval(Container.DataItem, "PostalCode") %>' runat="server" />
                        </ItemTemplate>
                    </asp:TemplateColumn>
                </Columns>
                <HeaderStyle HorizontalAlign="Center" />
            </asp:DataGrid>
            <br />
        </div> 
    </form>
</body>
</html>

Sample1.aspx.vb

Imports System.Data
Imports System.Data.SqlClient

Partial Class Sample1
    Inherits System.Web.UI.Page

    ' ----- Page Load Event -----
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not IsPostBack Then
            BindDataGridEmployees()
        End If

    End Sub
    ' ----- Page Load Event -----

    ' ----- DataGrid Bind Function -----
    Private Sub BindDataGridEmployees()

        Dim constr As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString

        Using mySqlConnection As SqlConnection = New SqlConnection(constr)

            mySqlConnection.Open()

            Dim mySqlCommand As SqlCommand = mySqlConnection.CreateCommand()
            ' sproc name
            mySqlCommand.CommandText = "NWEmployees_Get"
            mySqlCommand.CommandType = CommandType.StoredProcedure
            Dim mySqlDataAdapter As SqlDataAdapter = New SqlDataAdapter()
            mySqlDataAdapter.SelectCommand = mySqlCommand
            Dim ds As DataSet = New DataSet()
            mySqlDataAdapter.Fill(ds, "NWEmployees")
            DataGridEmployees.DataSource = ds.Tables("NWEmployees").DefaultView
            DataGridEmployees.DataBind()

            mySqlConnection.Close()

        End Using

    End Sub
    ' ----- DataGrid Bind Function -----

    ' ----- ASP CheckBox - Header Row Checkbox Changed Click Event -----
    Public Sub DataGridEmployees_SelectAll_Click(ByVal sender As Object, ByVal e As System.EventArgs)


    End Sub
    ' ----- ASP CheckBox - Header Row Checkbox Changed Click Event -----


    ' ----- Button Click - Check DataGrid Header CheckBox -----
    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        ' Check header checkbox

        'Call CheckHeaderCheckBox(sender, Me.DataGridEmployees)
        DataGridEmployees_SelectAll.Checked = True

    End Sub
    ' ----- Button Click - Check DataGrid Header CheckBox -----
    ' ----- Button Click - Uncheck DataGrid Header CheckBox -----
    Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        ' Uncheck header checkbox
        'Call UncheckHeaderCheckBox(sender, Me.DataGridEmployees)
        DataGridEmployees_SelectAll.Checked = False

    End Sub

    ' ----- Button Click - Uncheck DataGrid Header CheckBox -----

    ' ----- asp check box click event - good -----
    Protected Sub ChckedChanged(ByVal sender As Object, ByVal e As EventArgs)



    End Sub
    ' ----- asp check box click event - good -----

    ' ----- Function - Check Header CheckBox of DataGrid -----
    Private Sub CheckHeaderCheckBox(ByVal sender As Object, ByRef DG As Web.UI.WebControls.DataGrid)

        Dim targetChkBox As CheckBox = DataGridEmployees.Controls(0).Controls(0).FindControl("DataGridEmployees_SelectAll")
        targetChkBox.Checked = False

    End Sub
    ' ----- Function - Check Header CheckBox of DataGrid -----

    ' ----- Function - Uncheck Header CheckBox of DataGrid -----
    Private Sub UncheckHeaderCheckBox(ByVal sender As Object, ByRef DG As Web.UI.WebControls.DataGrid)

        Dim targetChkBox As CheckBox = DataGridEmployees.Controls(0).Controls(0).FindControl("DataGridEmployees_SelectAll")
        targetChkBox.Checked = False

    End Sub
    ' ----- Function - Uncheck Header CheckBox of DataGrid -----



End Class


In my Sample1.aspx my CheckBox is in the HeaderTemplate in this line of code:

                        <HeaderTemplate>
                            <asp:CheckBox runat="server" ID="DataGridEmployees_SelectAll" autopostback="true" OnCheckedChanged="DataGridEmployees_SelectAll_Click" />
                        </HeaderTemplate>

I noticed that if I get this checkbox and take it out of the DataGrid and just put it on the page somewhere, then the button click event recognizes the checkbox.


How do i fix my example so the Button clicks check or uncheck the check box that is in my DataGrid's HeaderTemplate?
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 2 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros