Persisting Checkbox State when Paging Gridview - asp.net

In a nutshell, I am trying to maintain the CheckBox state on a GridView while paging. I am successfully tracking the CheckBox states in the ViewState (using an ArrayList on the row IDs) and I can successfully perform an action on all the checked rows on multiple pages.
However, once I go to a new page and then page back, the checked CheckBoxes are no longer checked (though the row ID still exists in the ArrayList in the ViewState). I have to assume this has something to do with the page life cycle.
I have read the entire ASP.NET Page Life Cycle Overview and tried binding the GridView in the PreRender event (and not binding the GridView at all) which didn't work either. All the examples I found online were loading the GridView DataSource from code behind using a DataTable filled from a SQLDataAdapter. I am using a DataSourceID (from a SQLDataSource) assigned directly to the GridView.
I still can't seem to determine why this is failing. Thanks in advance for your time.
ASPX Page
<asp:SqlDataSource ID="sdsAdminIntakes" runat="server" CancelSelectOnNullParameter="false"
Connectionstring="<%$ ConnectionStrings:MyAppSiteDB %>"
ProviderName="<%$ ConnectionStrings:MyAppSiteDB.ProviderName %>"
SelectCommand="admin_intakes_search"
SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="specialist_id" />
<asp:Parameter Name="caller_name" />
<asp:Parameter Name="case_number" />
<asp:Parameter Name="case_status" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="grdAdminIntakes" runat="server"
DataKeyNames="intake_id" DataSourceID="sdsAdminIntakes"
AutoGenerateColumns="False" AllowSorting="True"
AllowPaging="True" PageSize="20">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox runat="server" ID="chkAll" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkIntake" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="specialist_full_name" HeaderText="Current Specialist"
SortExpression="specialist_full_name" >
</asp:BoundField>
<asp:BoundField DataField="caller_name" HeaderText="Caller"
SortExpression="caller_name" >
</asp:BoundField>
<asp:BoundField DataField="case_number" HeaderText="Case #"
SortExpression="case_number" >
</asp:BoundField>
<asp:BoundField DataField="cmp_status" HeaderText="Case Status"
SortExpression="case_status" ItemStyle-CssClass="case_status" >
</asp:BoundField>
</Columns>
</asp:GridView>
ASPX.VB Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
grdAdminIntakes.DataBind()
End If
End Sub
Private Sub grdAdminIntakes_PageIndexChanging(sender As Object, e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdAdminIntakes.PageIndexChanging
GetCheckboxState()
grdAdminIntakes.PageIndex = e.NewPageIndex
grdAdminIntakes.DataBind()
SetCheckboxState()
End Sub
Private Sub GetCheckboxState()
Dim lstArray As ArrayList
If ViewState("SelectedRecords") IsNot Nothing Then
lstArray = DirectCast(ViewState("SelectedRecords"), ArrayList)
Else
lstArray = New ArrayList()
End If
Dim chkAll As CheckBox = DirectCast(grdAdminIntakes.HeaderRow.Cells(0).FindControl("chkAll"), CheckBox)
For i As Integer = 0 To grdAdminIntakes.Rows.Count - 1
If chkAll.Checked Then
If Not lstArray.Contains(grdAdminIntakes.DataKeys(i).Value) Then
lstArray.Add(grdAdminIntakes.DataKeys(i).Value)
End If
Else
Dim chk As CheckBox = DirectCast(grdAdminIntakes.Rows(i).Cells(0).FindControl("chkIntake"), CheckBox)
If chk.Checked Then
If Not lstArray.Contains(grdAdminIntakes.DataKeys(i).Value) Then
lstArray.Add(grdAdminIntakes.DataKeys(i).Value)
End If
Else
If lstArray.Contains(grdAdminIntakes.DataKeys(i).Value) Then
lstArray.Remove(grdAdminIntakes.DataKeys(i).Value)
End If
End If
End If
Next
ViewState("SelectedRecords") = lstArray
End Sub
Private Sub SetCheckboxState()
Dim currentCount As Integer = 0
Dim chkAll As CheckBox = DirectCast(grdAdminIntakes.HeaderRow.Cells(0).FindControl("chkAll"), CheckBox)
chkAll.Checked = True
Dim lstArray As ArrayList = DirectCast(ViewState("SelectedRecords"), ArrayList)
For i As Integer = 0 To grdAdminIntakes.Rows.Count - 1
Dim chk As CheckBox = DirectCast(grdAdminIntakes.Rows(i).Cells(0).FindControl("chkIntake"), CheckBox)
If chk IsNot Nothing Then
chk.Checked = lstArray.Contains(grdAdminIntakes.DataKeys(i).Value)
If Not chk.Checked Then
chkAll.Checked = False
Else
currentCount += 1
End If
End If
Next
End Sub

After several more hours of research, I was finally able to get this working by moving the SetCheckboxState() out of the grdAdminIntakes_PageIndexChanging event and into the grdAdminIntakes_DataBound event.

Related

How to verify all button in approved in gridview while click on other button that is outside the gridview

I want to add one button in vb.net e.g bulk approval outside the gridview in another table. While clicking on that button I.e is bulk approval.. all verify button are verified in gridview in every row... and changed into verified.
Ok, so we have some kind of grid, and some kind of approve button for each row.
Ok, so we have some typical markup like this:
This is a grid (hotel bookings), and then a the "administrator" has to approve each one.
So, say some markup like this - nothing special:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" ItemStyle-Width="180" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Approved" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkApproved" runat="server" Checked='<%# Eval("Approved") %>'
CssClass="bigcheck" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="By">
<ItemTemplate>
<asp:Label ID="lblApBy" runat="server" Text='<%# Eval("ApprovedBy") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Approve">
<ItemTemplate>
<asp:Button ID="cmdApprove" runat="server" Text="Approve" CssClass="btn"
onclick="cmdApprove_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div style="float:right">
<asp:Button ID="cmdApproveAll" runat="server" Text="Approve All" CssClass="btn" />
And our code to load the grid:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String = "SELECT TOP 6 * from tblHotels"
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
Dim rstData As New DataTable
rstData.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = rstData
GridView1.DataBind()
End Using
End Using
End Sub
And we now have this:
Ok, so we have a plane jane button on each row. The code to approve a row is this code:
(a simple standard button in the grid view - button click)
Protected Sub cmdApprove_Click(sender As Object, e As EventArgs)
' approve one row
Dim btn As Button = sender
Dim gRow As GridViewRow = btn.NamingContainer
Call ApproveGRow(gRow)
End Sub
Sub ApproveGRow(gRow As GridViewRow)
' set checkbox = checked
Dim ckApprove As CheckBox = gRow.FindControl("chkApproved")
ckApprove.Checked = True
Dim lBy As Label = gRow.FindControl("lblApBy")
lBy.Text = UserInitials
' Get data base pk id
Dim pkID As Integer
pkID = GridView1.DataKeys(gRow.RowIndex).Item("ID")
' Now udpate database
Dim strSQL As String =
"UPDATE tblHotels SET Approved = 1, ApprovedBy = #Initials WHERE ID = #ID"
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
cmdSQL.Parameters.Add("#Initials", SqlDbType.NVarChar).Value = UserInitials
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = pkID
cmdSQL.ExecuteNonQuery()
End Using
End Using
End Sub
So, on a button click, we get the current row click, and then call our approve routine that accepts grid ro
So, if I click say on the second row, we see this:
However, what about do the WHOLE gird, with one button, and approve all rows?
Well, the button for the approve all looks like this:
Protected Sub cmdApproveAll_Click(sender As Object, e As EventArgs) Handles cmdApproveAll.Click
For Each gRow In GridView1.Rows
Call ApproveGRow(gRow)
Next
End Sub
And if I click on it, then I get this:

Check Row when changing pages in GridView

When clicking the pager in a GridView, I want to highlight each row if the amount equals a certain amount. I have this working when the GridView is first populated, but each time I click the pager button to move to the next page with a valid amount, it will not highlight. Any suggestions?
GridView
<asp:GridView ID="ERNDataGrid" runat="server" CssClass="clsGridView" AutoGenerateColumns="false" AllowPaging="true" PageSize="15"
OnPageIndexChanging="OnPageIndexChanging" OnRowDataBound="OnRowDataBound" Width="99%">
<HeaderStyle HorizontalAlign="Center" BackColor="#464646" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerSettings Mode="NextPreviousFirstLast" />
<PagerStyle HorizontalAlign="Right" ForeColor="White" BackColor="#464646" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False"></PagerStyle>
<AlternatingRowStyle BackColor="#DDDDDD"></AlternatingRowStyle>
<Columns>
<asp:BoundField DataField="CUID" HeaderText="Routing Number" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="Account" HeaderText="Account" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="Amount" HeaderText="Amount" DataFormatString="{0:C}" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="Serial" HeaderText="Check Number" ItemStyle-HorizontalAlign="Center" />
</Columns>
</asp:GridView>
VB.net Codebehind
Protected Sub ResearchGridView_Click(sender As Object, e As EventArgs) Handles ResearchGridView.Click
strResearchAmount = txtERNResearchAmount.Value
BindData()
End Sub
Private Sub ERNResearch_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
ERNDataGrid.DataBind()
End If
End Sub
Protected Sub BindData()
'Create a connection
Dim myConnection As New SqlConnection("This works")
'Create the command object, passing in the SQL string
Const strSQL As String = "SELECT CUID, Account, Amount / 100 as Amount, Serial FROM [ACCU].[dbo].[ERN_ITEM_VIEW] Where Date = '04/13/2017' And CUID <> '0'"
Dim myCommand As New SqlCommand(strSQL, myConnection)
'Create the DataAdapter
Dim myDA As New SqlDataAdapter()
myDA.SelectCommand = myCommand
'Populate the DataSet
Dim myDS As New DataSet()
myDA.Fill(myDS)
'Set the datagrid's datasource to the dataset and databind
ERNDataGrid.DataSource = myDS
ERNDataGrid.DataBind()
'Display Information on what page we are currently viewing
'lblMessage.Text = "Viewing Page " & ERNDataGrid.PageIndex + 1 & " of " & ERNDataGrid.PageCount
End Sub
Protected Sub OnPageIndexChanging(sender As Object, e As GridViewPageEventArgs)
ERNDataGrid.PageIndex = e.NewPageIndex
Me.BindData()
End Sub
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowIndex > -1 Then
If e.Row.Cells(2).Text = "$" & strResearchAmount Then
e.Row.BackColor = Color.Yellow
End If
End If
End Sub
Your code looks correct. The OnRowDataBound event is triggered every time DataBind() is called. And since that is the case in your OnPageIndexChanging the RowDataBound should fire.
However the strResearchAmount could be empty since it is filled only after a button click. Since a page index change also triggers a PostBack, it is likely that strResearchAmount is empty when OnRowDataBound is called for the second time.
Check the value of strResearchAmount and make sure it persists across PostBack.

copy row from asp.net gridview to new page using VB

I am trying to copy a row from a gridview to be displayed on a new page through a button in one of the columns in the gridview. I have my gridview populated from an Access database that is linked to my project. I have tried several different things, but nothing will display the row information when the project is ran. The current code I am trying from the actual dataview is:
Example 1a
<asp:GridView ID="Grid1" runat="server" Width ="90%" AutoGenerateColumns="false" OnRowDeleting="Grid1_RowDeleting" DataKeyNames="Title">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" />
<asp:BoundField DataField="Console" HeaderText="Console" />
<asp:BoundField DataField="Year_Released" HeaderText="Year Released" />
<asp:BoundField DataField="ESRB" HeaderText="ESRB Rating" />
<asp:BoundField DataField="Score" HeaderText="Personal Score" />
<asp:BoundField DataField="Publisher" HeaderText="Publisher" />
<asp:BoundField DataField="Developer" HeaderText="Developer" />
<asp:BoundField DataField="Genre" HeaderText="Genre" />
<asp:BoundField DataField="Purchase" HeaderText="Purchase Date" />
<asp:TemplateField ItemStyle-Width="7%" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lnkDetails" runat="server" Text="View" PostBackUrl='<%# "~/ViewDetails.aspx?RowIndex=" & Container.DataItemIndex %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the codebehind code on the page where I am trying to have the code be displayed is:
Example 1b
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Me.Page.PreviousPage IsNot Nothing Then
Dim rowIndex As Integer = Integer.Parse(Request.QueryString("RowIndex"))
Dim GridView1 As GridView = DirectCast(Me.Page.PreviousPage.FindControl("Grid1"), GridView)
Dim row As GridViewRow = GridView1.Rows(rowIndex)
lblTitle.Text = row.Cells(0).Text
lblConsole.Text = row.Cells(1).Text
lblYear.Text = row.Cells(2).Text
lblESRB.Text = row.Cells(3).Text
lblScore.Text = row.Cells(4).Text
lblPublisher.Text = row.Cells(5).Text
lblDeveloper.Text = row.Cells(6).Text
lblGenre.Text = row.Cells(7).Text
lblPurchase.Text = row.Cells(8).Text
End If
End Sub
I have also tried another set of code where the button on the gridview was:
Example 2a
<asp:Button ID="btnLink" runat="server" Text="View Details" PostBackUrl='<%# Eval("Title", "~/ViewDetails.aspx?Id={0}") %>'/>
Where the codebehind code is:
Example 2b
Protected Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
Dim GameTitle As String = Request.QueryString("Id")
Dim connString As String = "PROVIDER=Microsoft.ACE.OLEDB.12.0;" + "DATA SOURCE=" + Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "App_Data" + "db1.accdb")
Using connection As New OleDbConnection(connString)
connection.Open()
Dim reader As OleDbDataReader = Nothing
Dim command As New OleDbCommand((Convert.ToString("SELECT * from [Video_Games] WHERE Title='") & GameTitle) + "'", connection)
reader = command.ExecuteReader()
While reader.Read()
lblTitle.Text = reader(0).ToString()
lblConsole.Text = reader(1).ToString()
lblYear.Text = reader(2).ToString()
lblESRB.Text = reader(3).ToString()
lblScore.Text = reader(4).ToString()
lblPublisher.Text = reader(5).ToString()
lblDeveloper.Text = reader(6).ToString()
lblGenre.Text = reader(7).ToString()
lblPurchase.Text = Convert.ToDateTime(reader(8).ToString()).ToShortDateString()
End While
End Using
End If
End Sub
End Class
I have tried making variations of both, mainly the second, but whatever I try the labels are not populated with the row information. Any assistance would be appreciated, and I can post any other code needed, like how I populated the gridview. Thank you.
It was as simple as changing the AutoEventWireup to "true" in my .aspx file.

Selecting controls from a dynamically generated Grid View

Below is the code for a Grid View that I have. The Gird View is populated by a set of data returned from a database.
<asp:GridView ID="GridView1" runat="server" CellPadding="3" AutoGenerateColumns="False" EnableModelValidation="True">
<RowStyle BackColor="#000000" ForeColor="#8C4510" />
<FooterStyle BackColor="#000000" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#FF9933" Font-Bold="True" ForeColor="Black" />
<Columns>
<asp:TemplateField HeaderText="Requestor">
<ItemTemplate>
<asp:Label ID="Requestor" runat="server" Text='<%# Bind("REQUESTED_BY") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Card Number">
<ItemTemplate>
<asp:Label ID="CardNumber" runat="server" Text='<%# Bind("CARD_NUMBER") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Submitted">
<ItemTemplate>
<asp:Label ID="DateSubmitted" runat="server" Text='<%# Bind("DATE_SUBMITTED") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Confirm?">
<ItemTemplate>
<asp:CheckBox ID="chkConfirm" runat="server" Checked='<%# Bind("EMAIL_SENT") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" />
When a box is ticked in the Grid View, users should then be able to press a button that calls the ConfirmCards_Click Sub.
Protected Sub ConfirmCards_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ConfirmCards.Click
Dim NumberOfRows = GridView1.Rows.Count
Dim i As Integer = 0
Dim ConfirmValue As CheckBox
Dim CardNumber As Label
Dim CardsConfirmed As String
Dim RunNumber As Integer = 0
For i = 0 To NumberOfRows - 1
ConfirmValue = GridView1.Rows(i).FindControl("chkConfirm")
CardNumber = GridView1.Rows(i).FindControl("CardNumber")
MsgBox(ConfirmValue.Checked & " " & CardNumber.Text, vbOKOnly, "Card and checked status")
Next
End Sub
In the actual system, this sub would have funcitonality that marks a field in a database, confirming that the cards have been confirmed.
However, when clicking the button that calls the ConfirmCards_Click sub, the alertbox always comes back with False and the CardNumber of the rows, regradless of whether or not chkConfirm has been ticked.
How can I fix this? I have very similar code in another page that works just fine - is there some setting that needs to be applied to the page in order for the server to realise that the checkboxes have been ticked?
Edit: Including Page_Load VB code, as requested.
Public Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim qryRaisedCards As String
If TeamName.Text = "Admin" Then
qryRaisedCards = "select CARD_NUMBER, REQUESTED_BY, DATE_SUBMITTED, EMAIL_SENT from SUBMISSIONS where EMAIL_SENT = 0 order by DATE_SUBMITTED, CARD_NUMBER"
Else
qryRaisedCards = "select CARD_NUMBER, REQUESTED_BY, DATE_SUBMITTED, EMAIL_SENT from SUBMISSIONS where EMAIL_SENT = 0 and TEAM_NAME = :TeamName order by DATE_SUBMITTED, CARD_NUMBER"
End If
Using cn2 As New OracleConnection(ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString), _
cmd2 As New OracleCommand(qryRaisedCards, cn2)
If TeamName.Text <> "Admin" Then
cmd2.Parameters.Add(":TeamName", OracleDbType.Varchar2, 60).Value = TeamName.Text
End If
Dim RaisedCardsAdapter As New OracleDataAdapter(cmd2)
Dim RaisedCardsDataset As New DataSet()
RaisedCardsAdapter.Fill(RaisedCardsDataset, "UserPermissions")
cn2.Open()
cmd2.ExecuteNonQuery()
cn2.Close()
If RaisedCardsDataset.Tables(0).Rows.Count > 0 Then
ErrorMessage.Visible = False
GridView1.DataSource = RaisedCardsDataset
GridView1.DataBind()
Else
GridViewPanel.Visible = False
ErrorMessage.Visible = True
ErrorMessage.Text = "There are no submitted cards that have not been confirmed at this time."
End If
End Using
End Sub
From code what I see is your gridview is getting bound on postback also. Which causes loosing value of state with which it was posted back. try wraping your code of Page_Load in If not IsPostback then.
Public Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim qryRaisedCards As String
If Not IsPostBack Then
If TeamName.Text = "Admin" Then
qryRaisedCards = "select CARD_NUMBER, REQUESTED_BY, DATE_SUBMITTED, EMAIL_SENT from SUBMISSIONS where EMAIL_SENT = 0 order by DATE_SUBMITTED, CARD_NUMBER"
Else
qryRaisedCards = "select CARD_NUMBER, REQUESTED_BY, DATE_SUBMITTED, EMAIL_SENT from SUBMISSIONS where EMAIL_SENT = 0 and TEAM_NAME = :TeamName order by DATE_SUBMITTED, CARD_NUMBER"
End If
Using cn2 As New OracleConnection(ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString), _
cmd2 As New OracleCommand(qryRaisedCards, cn2)
If TeamName.Text <> "Admin" Then
cmd2.Parameters.Add(":TeamName", OracleDbType.Varchar2, 60).Value = TeamName.Text
End If
Dim RaisedCardsAdapter As New OracleDataAdapter(cmd2)
Dim RaisedCardsDataset As New DataSet()
RaisedCardsAdapter.Fill(RaisedCardsDataset, "UserPermissions")
cn2.Open()
cmd2.ExecuteNonQuery()
cn2.Close()
If RaisedCardsDataset.Tables(0).Rows.Count > 0 Then
ErrorMessage.Visible = False
GridView1.DataSource = RaisedCardsDataset
GridView1.DataBind()
Else
GridViewPanel.Visible = False
ErrorMessage.Visible = True
ErrorMessage.Text = "There are no submitted cards that have not been confirmed at this time."
End If
End Using
End If
End Sub

Checkbox on Datagrid for ASP

I have a data grid on my project with a Checkbox as a TemplateField; but I can't acces the checkbox.checked property. Does anyone have any idea?
My ASP code:
<asp:GridView ID="GVP" runat="server" AutoGenerateColumns="False" DataSourceID="DSP">
<Columns>
<asp:TemplateField HeaderStyle-Width="5%" ItemStyle-Width="5%" FooterStyle-Width ="5%">
<ItemTemplate>
<asp:CheckBox ID="SelectCb" runat="server"></asp:CheckBox>
</ItemTemplate>
<FooterStyle Width="5%"/>
<HeaderStyle Width="5%"/>
<ItemStyle Width="5%"/>
</asp:TemplateField>
<asp:BoundField DataField="Answers" HeaderText="Options" SortExpression="Answers" />
</Columns>
</asp:GridView>
My VB code behind:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonNext.Click
Dim SelectedBox As Boolean = False
For Each row As GridViewRow In GVP.Rows
Dim cb As CheckBox = row.FindControl("SelectCb")
If cb IsNot Nothing AndAlso cb.Checked Then
SelectedBox = True
Dim RID As Integer = Convert.ToInt32(GVP.DataKeys(row.RowIndex).Value)
Else
ShowMessage("You did not select anything")
End if
try this:
For Each row As GridViewRow In gvTest.Rows
Dim cb As CheckBox = row.FindControl("SelectCb")
If (CType(row.FindControl("SelectCb"), CheckBox)).Checked = True Then
SelectedBox = True
Dim RID As Integer = Convert.ToInt32(gvTest.DataKeys(row.RowIndex).Value)
End If
Next
It's hard to tell what you are trying to do here and how you are testing but my guess is that this is because you are not checking for row type. So the first row is actually the header and therefore will not have a checkbox at all (and you will get the message).
For Each row As GridViewRow In GVP.Rows
If row.RowType = DataControlRowType.DataRow Then
Dim cb As CheckBox ...
The problem really resided on the Page_Load where I was binding the grid to the datasource; I deleted it and the problem was solved.

Resources