Selecting controls from a dynamically generated Grid View - asp.net

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

Related

Persisting Checkbox State when Paging Gridview

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.

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.

Row command not working in gridview

Hi I am using following code to display a grid on aspx
<asp:GridView Caption="Search Results" ID="PhysicianGrid"
runat="server" EnableSortingAndPagingCallbacks="false" PageSize="5" Style="width: 100%"
PagerSettings-Visible="false" AutoGenerateColumns="false" CssClass="grid" RowStyle-CssClass="gridDataRow"
HeaderStyle-CssClass="headerRow" EnableViewState ="False">
<Columns>
<asp:TemplateField HeaderText="Select">
<HeaderStyle Width="70px" HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:LinkButton ID="SelectedPhysician" runat="server" Text="Select" CommandName="SelectAffiliation" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Physician ID" DataField="AMDM_Phys_ID" HeaderStyle-HorizontalAlign="Left"
ItemStyle-HorizontalAlign="Left" HeaderStyle-Width="70px" ItemStyle-Width="70px" />
</Columns>
</asp:GridView>
and following is the row bound function for the above grid
Private Sub PhysicianGrid_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles PhysicianGrid.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim selectLink As LinkButton = DirectCast(e.Row.FindControl("SelectedPhysician"), LinkButton)
Dim physId As String = e.Row.Cells(1).Text
If OperationType.Value.Equals("ADD ALLOCATION") Then
selectLink.OnClientClick() = String.Format("DisplayUpdateAllocationDivFromSearch('{0}');", physId)
Else
'selectLink.OnClientClick() = String.Format("DisplayUpdateAllocationDivFromSearchNewPhy('{0}');", physId)
selectLink.CommandArgument = physId
End If
selectLink.CommandArgument = physId
End If
End Sub
when I am clicking on the select link the application gets postback and hitting the page_load function but on the click event handler
Private Sub PhysicianGrid_Command(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles PhysicianGrid.RowCommand
If _requestView.CRTypeId = Resources.PageResources.CRTYPEAddNewPhysician AndAlso Request.Form("__EVENTTARGET").Contains("SelectedPhysician") AndAlso OperationType.Value.Equals("ADD NEW PHY") Then
Dim selectedPhys As Integer = CInt(e.CommandArgument)
Dim tempPhys As PhysicianView = New PhysicianView
tempPhys.LoadSearchPhysician(Master.Environment, selectedPhys, True)
Dim dt As ShipToDetailsDataSet.AMU_SHIPTO_ALLOCATION_VDataTable = New ShipToDetailsDataSet.AMU_SHIPTO_ALLOCATION_VDataTable
If allocationOperation.Value.Equals("UPDATE") Then
If GridSelectedShipToAllocations.Rows.Count > 0 Then
For Each row As GridViewRow In GridSelectedShipToAllocations.Rows
Dim allocationString As String = DirectCast(row.FindControl("TextBoxNewAllocation"), TextBox).Text
SaveGridAllocationChangeForPostback(allocationString)
dt.AddAMU_SHIPTO_ALLOCATION_VRow(CInt(_shipToID), CInt(row.Cells(GridSelectedShipToAllocations_columns.colAMDM_PHYS_ID).Text), row.Cells(GridSelectedShipToAllocations_columns.colPhysician_Name).Text, Nothing, CDec(row.Cells(GridSelectedShipToAllocations_columns.colAllocation).Text.Substring(0, row.Cells(GridSelectedShipToAllocations_columns.colAllocation).Text.Length - 1)), CDate("01/01/2007"), Nothing, "", "", "", row.Cells(GridSelectedShipToAllocations_columns.colMajorSpec).Text.Replace(" ", ""), row.Cells(GridSelectedShipToAllocations_columns.colSecondarySpecialty).Text.Replace(" ", ""), row.Cells(GridSelectedShipToAllocations_columns.colTertiarySpecialty).Text.Replace(" ", ""), "", "", "", "")
Next
End If
dt.AddAMU_SHIPTO_ALLOCATION_VRow(CInt(_shipToID), tempPhys.PhysicianID, String.Format("{0}, {1} {2}", tempPhys.LastName, tempPhys.FirstName, tempPhys.MiddleName), Nothing, 0, CDate("01/01/2007"), Nothing, tempPhys.StatusId, tempPhys.FirstName, tempPhys.LastName, tempPhys.MajorSpec, tempPhys.SECONDARY_SPECIALTY_LD, tempPhys.TERTIARY_SPECIALTY_LD, "", "", "", "")
GridSelectedShipToAllocations.DataSource = dt
GridSelectedShipToAllocations.DataBind()
GridSelectedShipToAllocations.Style("display") = "block"
'DivAddAllocationChange.Style("display") = "none"
LabelTotal.Style("display") = "block"
ScriptManager.RegisterStartupScript(Me.PhysicianGrid, GetType(Page), "hideSearchPhysDiv", "DisplayUpdateAllocationDivFromSearchNewPhy('" + selectedPhys.ToString + "');", True)
End If
End If
End Sub
how can I get it to hit the row command function
P.S. I need to use the EnableViewState ="False" attribute in the grid I cant remove this attribute. Is there any workaround to this issue?
This is how I achieved it in a recent project, may be it could help you find the problem. The command argument has been specified in the ASPX instead of RowDataBound event.
As a work around you may just comment out the code in your RowDataBound event and set CommandArgument in ASPX and check what happens.
Also I think instead of Request.Form("__EVENTTARGET").Contains("SelectedPhysician") you may try e.CommandName.Equals("SelectedPhysician")
ASPX:
<asp:GridView ID="gvStudents" runat="server" AutoGenerateColumns="false">
<Columns>
...
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="BtnUnlock" runat="server" Text="Unlock" CausesValidation="True" CommandName="UnlockProfile" CommandArgument='<%# Eval("User_ID") %>' />
</ItemTemplate>
</asp:TemplateField>
...
</Columns>
</asp:GridView>
CodeBehind:
Private Sub gvStudents_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvStudents.RowCommand
If e.CommandName.Equals("UnlockProfile") Then
Dim lnUser_ID As Integer = Convert.ToInt32(e.CommandArgument)
...
ElseIf e.CommandName.Equals("LockProfile") Then
...
End If
End Sub

How to get data from one page (databound) to another page's textbox in asp.net

Suppose I have two .aspx pages and a connection the the sql server database engine.
The first page, let's call it playground.aspx, I'm having a set of databound which using the stored procedure for SELECT function (using dataset for it).
Now in the second page, let's call it link.aspx, there are two textbox, suppose there are multiple data in the playground.aspx page and I want to retrieve Entity Code and Username data (from the playground.aspx's databound) and show it in the link.aspx's textbox.
How can I do that?
I was told to create some function, but I never dealt with a databound before, only with TextBox and Label, it really confused me.
Any help's appreciated, thank you.
EDIT (Here's the databound code)
<asp:Panel ID="PanelDGV" runat="server" Height="100%" ScrollBars="None" Width="100%">
<asp:GridView ID="DGV" runat="server" AutoGenerateColumns="False" GridLines="None"
AllowPaging="true" PageSize="2" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
<Columns>
<asp:BoundField DataField="EntityCode" HeaderText="Entity Code" />
<asp:BoundField DataField="UserName" HeaderText="Username" />
<asp:BoundField DataField="DivCode" HeaderText="Div Code" />
<asp:BoundField DataField="GroupCode" HeaderText="Group Code" />
<asp:BoundField DataField="CreatedBy" HeaderText="Created By" />
<asp:BoundField DataField="CreatedOn" HeaderText="Created On" />
<asp:BoundField DataField="ModifiedBy" HeaderText="Modified By" />
<asp:BoundField DataField="ModifiedOn" HeaderText="Modified On" />
<asp:ButtonField ButtonType="Image" ImageUrl="../Support/Image/Edit.png" ItemStyle-HorizontalAlign="Center"
CommandName="CmdEdit" HeaderText="Edit">
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:ButtonField>
</Columns>
<PagerStyle CssClass="pgr"></PagerStyle>
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
</asp:GridView>
</asp:Panel>
I just solved the problem, here's the code
For link.vb
Public Function F01_sysUser_Select(ByVal EntityCode As String, ByVal Username As String) As ProcessResult
Try
Dim SqlCmd As New SqlCommand()
SqlCmd.Connection = New SqlConnection(CF.CfgConnectionString)
SqlCmd.CommandType = CommandType.StoredProcedure
SqlCmd.CommandTimeout = CF.CfgCommandTimeout
SqlCmd.CommandText = "sysUser_SelectByID"
SqlCmd.Parameters.Add("#EntityCode", SqlDbType.VarChar) : SqlCmd.Parameters(0).Value = EntityCode
SqlCmd.Connection.Open()
Dim Dr As SqlDataReader = SqlCmd.ExecuteReader(CommandBehavior.CloseConnection)
F01_Dt_sysUser.Clear()
F01_Dt_sysUser.Load(Dr)
If F01_Dt_sysUser.Rows.Count > 0 Then
Dr.Close()
Dr = Nothing
SqlCmd.Dispose()
Return ProcessResult.SuccessWithResult
Else
Dr.Close()
Dr = Nothing
SqlCmd.Dispose()
Return ProcessResult.SuccessWithNoResult
End If
Catch ex As Exception
InsertErrorLog("PlaygroundLink.F01_sysUser_Select", ex.Message)
ExMessage = ex.Message
Return ProcessResult.Failed
End Try
End Function
and in the link.aspx.vb:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim QSEntityCode As String
Dim QSUserName As String
QSEntityCode = Request.QueryString("QSEC").ToString
QSUserName = Request.QueryString("QSUN").ToString
Dim Bl As New PlaygroundLink
If Bl.F01_sysUser_Select(QSEntityCode, QSUserName) = CF.ProcessResult.SuccessWithResult Then
TbEntityCode.Text = QSEntityCode
TbUsername.Text = QSUserName
Else
' LblMessage.Text = Bl.ExMessage
End If
End Sub
lastly in playground.aspx.vb:
Private Sub DGV_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles DGV.RowCommand
If e.CommandName = "CmdEdit" Then
Dim QSEntityCode As String
Dim QSUserName As String
Dim idx As Integer = Convert.ToInt32(e.CommandArgument)
Dim row As GridViewRow = DGV.Rows(idx)
QSEntityCode = row.Cells(0).Text
QSUserName = row.Cells(1).Text
Response.Redirect(RR.PlaygroundLink & "?QSEC=" & QSEntityCode & "&QSUN=" & QSUserName)
End If
End Sub
After that, I get what I want, displaying the result in the link.aspx textbox, cheers! :)

Why isn't the new values pulling up when I update the GridViewRow?

So what's happening is that I click the Edit button, type the updated values and hit Update. But the code-behind gets the original values not the updated values. I can't figure out why. It's always worked before.
Markup
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
CellPadding="7" ForeColor="#333333" GridLines="None" Font-Size="Small"
ShowFooter="True" DataKeyNames="CapID">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="AllocationId">
<ItemTemplate>
<asp:Label ID="show" runat="server" Text='<%# Eval("CapID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reference Number">
<ItemTemplate>
<asp:Label ID="showRefNo" runat="server" Text='<%# Eval("RefNo") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="EditRefNo"
Text='<%# Bind("RefNo") %>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="InsertRefNo"
Text='<%# Bind("RefNo") %>'/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Resource">
<ItemTemplate>
<asp:Label ID="showResource" runat="server"
Text='<%# Eval("Resource") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="EditResource"
Text='<%# Bind("Resource") %>'/>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="InsertResource"
Text='<%# Bind("Resource") %>'/>
</FooterTemplate>
</asp:TemplateField>
<!-- and so on... -->
</Columns>
<!-- styles etc -->
<EmptyDataTemplate>
Ref Num: <asp:TextBox ID="newRefNo" runat="server"/>
Resource: <asp:TextBox ID="newResource" runat="server"/>
Hours Allocated: <asp:TextBox ID="newHours" runat="server"/>
Week Offset: <asp:TextBox ID="newOffset" runat="server"/>
<asp:Button runat="server" ID="NewDataInsert"
CommandName="NewDataInsert" Text="Insert"/>
</EmptyDataTemplate>
</asp:GridView>
Code Behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
If Not IsPostBack Then
GridView1_DataBind()
GridView2_DataBind()
End If
End Sub
Protected Sub GridView2_RowUpdating(ByVal sender As Object, ByVal e As
GridViewUpdateEventArgs) Handles GridView2.RowUpdating
Dim capID As Label = GridView2.Rows(e.RowIndex).Cells(0)
.FindControl("show")
Dim refNo As TextBox = GridView2.Rows(e.RowIndex).Cells(1)
.FindControl("EditRefNo")
Dim resource As TextBox =
GridView2.Rows(e.RowIndex).Cells(2).FindControl("EditResource")
Dim hours As TextBox =
GridView2.Rows(e.RowIndex).Cells(3).FindControl("EditHours")
Dim offSet As TextBox =
GridView2.Rows(e.RowIndex).Cells(4).FindControl("EditOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim updateRows As DataRow() =
newResAlloc.Select("CapID = " & "'" & capID.Text & "'")
If (Not updateRows Is Nothing) And updateRows.Length > 0 Then
For Each updRow As DataRow In updateRows
updRow.BeginEdit()
updRow.Item("Refno") = refNo.Text
updRow.Item("Resource") = resource.Text
updRow.Item("Hours") = hours.Text
updRow.Item("Offset") = offSet.Text
updRow.EndEdit()
Next
End If
resourceInfo.updateResAllocations(newResAlloc)
GridView2.EditIndex = -1
GridView2_DataBind()
End Sub
This could be a million and one things. What have you checked? Have you narrowed it down?
Here's some starting points for you:
Put a breakpoint inside GridView2_RowUpdating to make sure it's being called.
Check the value of capID, or capID.Text - it shouldn't be 0.
Check that your database table contains a row where CapID equals the value of capID.Text
Put a breakpoint on updateRows to ensure that the database row is being loaded into your code.
Make sure that the updRow.EndEdit() is being hit, and that the values are populated into the row correctly.
Finally, check that the updateResAllocations is working properly. It's impossible to see from here how it works, so I can't give any advice on that.
The easiest way to fix this might be to ask whoever wrote it for some assistance.
The problem was that my RowCommand method was calling the DataBind
Wrong way:
Protected Sub GridView2_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles GridView2.RowCommand
If e.CommandName = "NewDataInsert" Then
Dim refNo As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewRefNo")
Dim resource As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewResource")
Dim hours As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewHours")
Dim offset As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim newAllocRow As DataRow = newResAlloc.NewRow
newAllocRow.ItemArray = New Object() {Nothing, refNo.Text, resource.Text, hours.Text, offset.Text}
newResAlloc.Rows.Add(newAllocRow)
resourceInfo.updateResAllocations(newResAlloc)
ElseIf e.CommandName = "InsertNew" Then
Dim refNo As TextBox = GridView2.FooterRow.FindControl("InsertRefNo")
Dim resource As TextBox = GridView2.FooterRow.FindControl("InsertResource")
Dim hours As TextBox = GridView2.FooterRow.FindControl("InsertHours")
Dim offset As TextBox = GridView2.FooterRow.FindControl("InsertOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim newAllocRow As DataRow = newResAlloc.NewRow
newAllocRow.ItemArray = New Object() {Nothing, refNo.Text, resource.Text, hours.Text, offset.Text}
newResAlloc.Rows.Add(newAllocRow)
resourceInfo.updateResAllocations(newResAlloc)
End If
GridView2_DataBind() 'Culprit
End Sub
Right way:
Protected Sub GridView2_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles GridView2.RowCommand
If e.CommandName = "NewDataInsert" Then
Dim refNo As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewRefNo")
Dim resource As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewResource")
Dim hours As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewHours")
Dim offset As TextBox = GridView2.Controls(0).Controls(0).FindControl("NewOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim newAllocRow As DataRow = newResAlloc.NewRow
newAllocRow.ItemArray = New Object() {Nothing, refNo.Text, resource.Text, hours.Text, offset.Text}
newResAlloc.Rows.Add(newAllocRow)
resourceInfo.updateResAllocations(newResAlloc)
GridView2_DataBind() 'Only called if IF is true
ElseIf e.CommandName = "InsertNew" Then
Dim refNo As TextBox = GridView2.FooterRow.FindControl("InsertRefNo")
Dim resource As TextBox = GridView2.FooterRow.FindControl("InsertResource")
Dim hours As TextBox = GridView2.FooterRow.FindControl("InsertHours")
Dim offset As TextBox = GridView2.FooterRow.FindControl("InsertOffset")
Dim newResAlloc As DataTable = resourceInfo.loadResAllocations
Dim newAllocRow As DataRow = newResAlloc.NewRow
newAllocRow.ItemArray = New Object() {Nothing, refNo.Text, resource.Text, hours.Text, offset.Text}
newResAlloc.Rows.Add(newAllocRow)
resourceInfo.updateResAllocations(newResAlloc)
GridView2_DataBind() 'Only called if IF is true
End If
End Sub

Resources