Solved

GridView problems ... Foreach loop help needed

Posted on 2014-10-07
13
292 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
  • 7
  • 3
  • 2
  • +1
13 Comments
 
LVL 39

Assisted Solution

by:Kyle Abrahams
Kyle Abrahams earned 250 total points
Comment Utility
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
Comment Utility
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
Comment Utility
>>  chk = (CheckBox)(rowItem.Cells[0].FindControl("chkRow"));
Should be
CheckBox chk = (CheckBox)rowItem.FindControl("chkRow");
0
 
LVL 5

Author Comment

by:Bob Bender
Comment Utility
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
Comment Utility
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
Comment Utility
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 8

Expert Comment

by:johny_bravo1
Comment Utility
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
Comment Utility
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 39

Expert Comment

by:Kyle Abrahams
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
working together to get a solution...  Thanx to both of ya!!!!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

763 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now