Solved

GridView problems ... Foreach loop help needed

Posted on 2014-10-07
13
317 Views
Last Modified: 2014-10-08
Making the way into GridView programming and losing my mind...

First, my 2 databases, with a composite key....  (Filtered here for simple look)

TABLE [dbo].[Table1](
	[Tab1RequestDate] [datetime] NOT NULL,
	[Tab1RequestType] [char](20) NOT NULL,
	[Tab1EmpID] [char](6) NOT NULL,
	[Tab1EmpLastName] [varchar](30) NULL,
	[Tab1EmpFirstName] [varchar](30) NULL,
	[Tab1HireMgrID] [char](6) NULL,
	[Tab1SentFeedback] [bit] NULL,
	[Tab1CompletionDate] [date] NULL,
 CONSTRAINT [PK_Tab1_Request] PRIMARY KEY CLUSTERED 
(
	[Tab1RequestDate] ASC,
	[Tab1EmpID] ASC
)
 

TABLE [dbo].[Table2](
	[Tab2RequestDate] [datetime] NOT NULL,
	[Tab2EmpID] [char](6) NOT NULL,
	[Tab2EmpLastName] [varchar](30) NULL,
	[Tab2EmpFirstName] [varchar](30) NULL,
	[Tab2MgrID] [char](6) NULL,
	[Tab2SentFeedback] [bit] NULL,
	[Tab2CompletionDate] [date] NULL,
 CONSTRAINT [PK_Tab2_Request] PRIMARY KEY CLUSTERED 
(
	[Tab2RequestDate] ASC,
	[Tab2EmpID] ASC
)

Open in new window



My Gridview definition....   DATAKEY Is what is not friendly to me.... (More in CS logic)

aspx file logic
         <asp:GridView ID="FeedbackGridView" runat="server"
                Font-Size="1em"
                AutoGenerateColumns="False"
                AllowPaging="True"
                CellPadding="5"
                CellSpacing="3"
                DataKeyNames="?????????????????????????????? HELP!!!!!!"
                DataSourceID="FeedbackDataSource"
                HeaderStyle-HorizontalAlign="Center"
                HeaderStyle-Wrap="true"
                HorizontalAlign="Center"
                SelectedRowStyle-BackColor="Wheat" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" 
                OnSelectedIndexChanged="FeedbackGridView_SelectedIndexChanged">
                <Columns>
                    <asp:TemplateField
                        ItemStyle-CssClass="centered">
                        <HeaderTemplate>
                            <asp:Label ID="Label1" runat="server"
                                Font-Size=".9em"
                                Text="Select All" />
                            <asp:CheckBox ID="chkHeader" runat="server" />
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:CheckBox ID="chkRow" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="OnOffFlag" HeaderText="Type" ReadOnly="True" />
                    <asp:BoundField DataField="RequestDateYYYYMMDD" HeaderText="Request Date" DataFormatString="{0:d}" ItemStyle-HorizontalAlign="Center" ReadOnly="True" />
                    <asp:BoundField DataField="Tab1HireMgrID" HeaderText="Manager ID" ItemStyle-HorizontalAlign="Center" ReadOnly="True" />
                    <asp:BoundField DataField="Tab1EmpID" HeaderText="New Hire ID" ItemStyle-HorizontalAlign="Center" ReadOnly="True" />
                    <asp:BoundField DataField="EmpName" HeaderText="New Hire Name" ReadOnly="True" />
                    <asp:BoundField DataField="Tab1RequestType" HeaderText="New Hire Type" ReadOnly="True" ItemStyle-HorizontalAlign="Center" />
                    <asp:BoundField DataField="Tab1CompletionDate" HeaderText="Date Completed" DataFormatString="{0:d}" ItemStyle-HorizontalAlign="Center" ReadOnly="True" />
                </Columns>
                <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />

                <HeaderStyle HorizontalAlign="Center" Wrap="True" BackColor="#A55129" Font-Bold="True" ForeColor="White"></HeaderStyle>

                <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
                <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />

                <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White"></SelectedRowStyle>
            </asp:GridView>

            <asp:SqlDataSource ID="FeedbackDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:digitallifeConnectionString %>" SelectCommand="SELECT 
'Onboard' as OnOffFlag
,CONVERT (DATE, Tab1RequestDate) as RequestDateYYYYMMDD
,Tab1RequestDate
,Tab1HireMgrID
,Tab1RequestType
,Tab1EmpID
,Tab1FirstName + ' ' + Tab1LastName as EmpName
,Tab1CompletionDate
FROM dbo.Table1 as tbl_on
WHERE (tbl_on.CompletionDate Is Null) AND (tbl_on.SentFeedback Is Null)

UNION

SELECT
'Offboard' as OnOffFlag
,CONVERT (DATE, RequestDate) as RequestDateYYYYMMDD
,Tab2RequestDate
,Tab2HireMgrID
,' ' as Tab2RequestType
,Tab2EmpID
,Tab2EmpFirstName + ' ' + Tab2EmpLastName as EmpName
,CompletionDate
FROM dbo.Table2 as tbl_off
WHERE (tbl_off.CompletionDate Is Null) AND (tbl_Off.SentFeedback Is Null)
ORDER BY RequestDateYYYYMMDD ASC">
</asp:SqlDataSource>

Open in new window



Now, the .cs code-behind  executed when btnSubmit (Send Email Requests) is hit.  

        protected void btnSubmit_OnClick(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                CheckBox chk;

                foreach (GridViewRow rowItem in FeedbackGridView.Rows)
                {
                    // FindControl function gets the control placed inside the GridView control from the specified cell
                    // FindControl fucntion accepts string id of the control that you want to access
                    // type casting of control allows to access the properties of that particular control
                    // here checkbox control type cast is used to access its properties
                    chk = (CheckBox)(rowItem.Cells[0].FindControl("chkRow"));
                    
                    // chk.checked will access the checkbox state on button click event
                    if (chk.Checked)
                    {
                        Response.Write(FeedbackGridView.DataKeys[rowItem.RowIndex]["categoryID"].ToString() + "<br />");	
//		Will SEND MAIL here fr each checked box...
                    }
                }
            }
        }

Open in new window


Build and set up....  I get an "Object reference not set to an instance of an object."  Know what it means...  but where?

Basic trouble... loop the table, send an email with each checked entry....  then update the Table1 or table2 Feedback sent.
BenderGrid.JPG
0
Comment
Question by:Bob Bender
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 3
  • 2
  • +1
13 Comments
 
LVL 40

Assisted Solution

by:Kyle Abrahams
Kyle Abrahams earned 250 total points
ID: 40366268
You have to check if the row Is a header row versus a data row.  The checkbox isn't displayed on the header row which is your problem.  


Chk is null on the header row at
 chk = (CheckBox)(rowItem.Cells[0].FindControl("chkRow"));
                    .
0
 
LVL 11

Expert Comment

by:louisfr
ID: 40366323
For the DataKeyNames property, you have an example at http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeynames.aspx. Use a comma-separated list:
DataKeyNames="Tab1RequestDate,Tab1EmpID"

Open in new window

0
 
LVL 8

Expert Comment

by:johny_bravo1
ID: 40366326
>>  chk = (CheckBox)(rowItem.Cells[0].FindControl("chkRow"));
Should be
CheckBox chk = (CheckBox)rowItem.FindControl("chkRow");
0
Certified OpenStack Administrator Course

We just refreshed our COA course based on the Newton exam.  With 14 labs, this course goes over the different OpenStack services that are part of the certification: Dashboard, Identity Service, Image Service, Networking, Compute, Object Storage, Block Storage, and Orchestration.

 
LVL 5

Author Comment

by:Bob Bender
ID: 40366396
Okay, to understand between the comments of Kyle and Johny...

Kyle...  Ya said the Checkbox on the HeaderRow is NOT displayed.   I thought the header is the line with the SELECT ALL and checkbox....   (True, I want to check the data rows, (ChkRow)... but I thought that would not reference the Header) . Does rowItem.Cells[0] refer to the header entry to "select all"?   After all that is a ROW in the total look of the GV.  Help me understand.  

Johny....  And to expand on my comment to Kyle,  changing the rowitems.cells[0] in my line to rowItem makes it look ONLY at entries that have the ChkRow  'name'?
0
 
LVL 5

Author Comment

by:Bob Bender
ID: 40366419
Louisfr....   So, the datakeys really refer to whatever makes up the primary key of the database????  

And if they are not 'defined',  I can check certain events to get the datakey from the 'e' object.?  At least that is what I think I understand?
0
 
LVL 5

Author Comment

by:Bob Bender
ID: 40366648
I Added a trace option to the Page Directives.   When I click the "Submit" button,

The Trace gives me...

aspx.page Begin ProcessPostData Second Try 0.00110729427101207 0.000022 
aspx.page End ProcessPostData Second Try 0.00112649313136772 0.000019 
aspx.page Begin Raise ChangedEvents 0.00114761187775894 0.000021 
aspx.page End Raise ChangedEvents 0.00117353033923906 0.000026 
aspx.page Begin Raise PostBackEvent 0.00119368914261249 0.000020 
Unhandled Execution Error 
Object reference not set to an instance of an object.
  at Portal.Admin.FeedBack_Requester.btnSubmit_OnClick(Object sender, EventArgs e)
  at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
  at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
  at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
  at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
  at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
  at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) 

Open in new window


Never used this much....   Could it possible be related to a jquery routine that handles the checkmarks?

Trying to find ideas....
0
 
LVL 8

Expert Comment

by:johny_bravo1
ID: 40366737
Hi Bob Bender,

You are using TemplateFields so you can get the Controls in the ItemTemplate directly, no need to do Cells[0]

Have you tried?
0
 
LVL 5

Author Comment

by:Bob Bender
ID: 40366847
I had changed the statement based on the comments here, but still have the Object Error....

to which I posted the trace that I added to directive....
0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 40367149
Try the following:
  if (chk != null && chk.Checked)
                    {
                      bool isNull = false;

//just debugging
                          if (FeedbackGridView.DataKeys[rowItem.RowIndex] == null)
                             //set breakpoint here.  
                                  isNull = true;
                          else if (FeedbackGridView.DataKeys[rowItem.RowIndex]["categoryID"] == null)
                            //also set here.
                                isNull = true;
 

                        Response.Write(FeedbackGridView.DataKeys[rowItem.RowIndex]["categoryID"].ToString() + "<br />");      
//            Will SEND MAIL here fr each checked box...
                    }
  else if (chk == null)
   //debug, set a break point here, should never be reached.
              chk = chk;
0
 
LVL 8

Accepted Solution

by:
johny_bravo1 earned 250 total points
ID: 40367643
Try
foreach (GridViewRow GR in GridView1.Rows)
{
     if (GR.RowType == DataControlRowType.DataRow)
        {  
CheckBox chk = (CheckBox)(GR.FindControl("chkRow"));
        }
}
0
 
LVL 5

Author Comment

by:Bob Bender
ID: 40368666
johny_bravo1... This line  [ if (GR.RowType == DataControlRowType.DataRow) ] is making us look at DataItems and not HeaderRows?  As outlined in the ItemTemplate?
0
 
LVL 5

Author Comment

by:Bob Bender
ID: 40368680
Kyle....   Makes sense, and lead me to using some more Response.Write's to find the process of what is happening.

All along, the problem was with the DataKeys in a way,  Not properly defined as CategoryID,  Missed that from the sample I used for starters.

You and Johny have been both instrumental in moving me forward.
0
 
LVL 5

Author Closing Comment

by:Bob Bender
ID: 40368683
working together to get a solution...  Thanx to both of ya!!!!
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

628 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question