Button Update in gridview and get value from hidden textbox - asp.net

The button in the gridview can't get the correct value from the hidden textbox.
Here is the code:
asp:
<columns>
<asp:TemplateField >
<ItemTemplate>
<asp:TextBox ID="txtFruit" runat="server" Visible="true" Text='<%# Bind("txtFruit")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="HiddentxtFruit" HeaderText ="Fruit" HeaderStyle-Width="0%" HtmlEncode="false" Visible="false" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Confirm">
<ItemTemplate>
<asp:Button ID="btnSubmit" Text="Confirm" runat="server" CommandName="Submit" />
</ItemTemplate>
</asp:TemplateField>
</columns>
code behind:
For intX As Integer = 0 To gridview1.Rows.Count - 1
Dim txtPLACE As TextBox = TryCast(gridview1.Rows(0).Cells(0).FindControl("txtFruit"), TextBox)
Next
or
For intX As Integer = 0 To gridview1.Rows.Count - 1
Dim txtPLACEss As TextBox = DirectCast(gridview1.Rows(intX).FindControl("txtFruit"), TextBox)
Next
This will only get the first row from the gridview.

use below code to get index of the row:
Dim rowIndex = DirectCast(DirectCast(sender, Control).NamingContainer, GridViewRow).RowIndex
And then
Dim txtPLACEss As TextBox = DirectCast(gridview1.Rows(rowIndex).FindControl("txtFruit"), TextBox)
That will solve your problem
UPDATE :
<asp:TemplateField >
<ItemTemplate><asp:TextBox ID="txtFruit" runat="server" Visible="true" Text='<%# Bind("txtFruit")%>' /></ItemTemplate></asp:TemplateField>
<asp:TextBox ID="txtFruitHidden" runat="server" Text='<%# Bind("txtFruit")%>' HeaderStyle-Width="0%" HtmlEncode="false" Visible="false" />
</asp:TemplateField>
Then in C#
Dim txtPLACEss As TextBox = DirectCast(gridview1.Rows(rowIndex).FindControl("txtFruitHidden"), TextBox)
Hope this will resolve your problem ..

Related

Error while binding data in GridView through Row Bound Event

I have following gridview in aspx page:
<asp:GridView Runat="server" id="gv1" PageSize="20" Visible="False" AllowPaging="True" Width="100%"
CssClass="clsDataGrid" AutoGenerateColumns="false" DataKeyNames="intProofSLNo,txtAdminRemarks" CommandArgument='Eval(intProofSLNo,txtAdminRemarks)'
OnRowCommand="gv1_RowCommand" OnRowDataBound ="gv1_OnRowDataBound" >
<asp:BoundField DataField="intProofSLNo" ReadOnly="True" Visible="false" ItemStyle-Wrap="false" HeaderText="Sl No" ItemStyle-CssClass="clsNormalText"></asp:BoundField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnApprove" runat="server" CommandName="Approve" Text= "Approve / " />
<asp:LinkButton ID="lnkbtnReject" runat="server" CommandName="Reject" Text= "Reject" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Admin Remarks">
<ItemTemplate>
<asp:Label ID="lblAdminRemarks" runat="server" ItemStyle-Wrap="True" Text='<%# Bind("txtAdminRemarks")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAdminRemarksEdit" runat="server" cssclass=clsCommonInput MaxLength="252" Text='<%# DataBinder.Eval(Container.DataItem, "txtAdminRemarks")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="lblEdit" runat="server" Text="Edit" ToolTip="Edit" CommandName="Edit" CommandArgument='<%# Container.DataItemIndex %>'>
</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" Width="38" runat="server" Text="Update|" CommandName="Update"CommandArgument='<%# Container.DataItemIndex %>' CausesValidation="true" ToolTip="Save"> </asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" Width="40" Text="Cancel" CommandName="Cancel"
CausesValidation="false" ToolTip="Reset"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The user clicks on the 'Edit' link which makes 'Update' and 'Cancel' links visible.It then enters the remarks in the textbox and clicks 'Update'.A row command event is fired which updates the remarks in DB for the entry in that particular row. The same event calls the bind function:
Protected Sub gv1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
If e.CommandName = "Update" Then
//some code to update remarks//
gv1.EditIndex = -1
subBindDataGrid()
End If
The subBindDataGrid() fires the following rowbound event which hides the buttons depending on admin remarks:
Protected Sub gv1_OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim lblAdminRemarks As Label = DirectCast(e.Row.FindControl("lblAdminRemarks"), Label)
Dim lnkReject As LinkButton = DirectCast(e.Row.FindControl("lnkbtnReject"), LinkButton)
Dim lnkApprove As LinkButton = DirectCast(e.Row.FindControl("lnkbtnApprove"), LinkButton)
Dim lnkEdit As LinkButton = DirectCast(e.Row.FindControl("lblEdit"), LinkButton)
If DataBinder.Eval(e.Row.DataItem, "txtAdminRemarks").ToString().Trim = "Auto-Approved" Then
lnkApprove.Visible = False
lnkReject.Visible = False
lnkEdit.Visible = False
Else
lnkbtnApprove.Visible = True
lnkbtnReject.Visible = True
End If
End If
The remarks get updated in the DB. However, there is some issue in binding and instead of displaying the grid, the page is redirected to an error page. There is no exception thrown anywhere while debugging. The same events are also called in 'Edit'command. However, the functionality works fine there.Please suggest if there is anything wrong with the syntax.
I see you don't define a DataSourceID on the GridView static definition, please make sure you define a DataSource for the GridView in the subBindDataGrid procedure, otherwise it will have a null datasource in input.

Filtering GridView rows not working

I've written some code in the Page_PreRender event that gets the value of a DropDownList control and then performs some conditional logic. Problem is, the logic must not be very good.
The first If.. Then.. Else.. structure is working fine, however, if the selectedItem is not "Todos" (portuguese for "all") all the rows' visibility will be set to false. The issue seems to arise when the If SelectedItem <> "Todos" Then condition is met.
So, every option in the DropDownList aside from "Todos" sets the visibility of all rows to False instead of setting the visibility of the ones that don't match the SelectedItem to False.
Protected Sub Page_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
'Getting the selected item
Dim SelectedItem As String = CType(GridView1.HeaderRow.Cells(3).FindControl("DropDownList1"), DropDownList).SelectedItem.Text
If SelectedItem <> "Todos" Then
'This is the part where the issue seems to be located.
For Each Row As GridViewRow In GridView1.Rows
'Get the Text value
Dim depar As String = Row.Cells(3).Text
'If its different from the SelectedItem then the row's visible property should be set to false, if it's a match, set it to true.
If depar <> SelectedItem Then
Row.Visible = False
ElseIf depar = SelectedItem Then
Row.Visible = True
End If
Next
'If "Todos" was selected, all rows should be visible
ElseIf SelectedItem = "Todos" Then
'Make all rows visible
For Each row As GridViewRow In GridView1.Rows
row.Visible = True
Next
End If
End Sub
Code of GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" PageSize="20" Width="100%" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%#CType(Container, GridViewRow).DataItem("IdPedido") %>' OnClick="LinkButton1_Click" OnCommand="LinkButton1_Command">Ver</asp:LinkButton>
</ItemTemplate>
<HeaderStyle Width="40px" />
</asp:TemplateField>
<asp:BoundField DataField="Observacoes" HeaderText="Assunto" SortExpression="Observacoes" />
<asp:BoundField DataField="NomeHotel" HeaderText="Hotel" SortExpression="NomeHotel" />
<asp:TemplateField HeaderText="Departamento" SortExpression="NomeDepartamento">
<HeaderTemplate>
Departamento<br />
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True" DataSourceID="SqlDataSource1" DataTextField="NomeDepartamento" DataValueField="IdDepartamento" AutoPostBack="True" OnLoad="DropDownList1_Load" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>Todos</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EnotelSuporteConnectionString1 %>" SelectCommand="SELECT [NomeDepartamento], [IdDepartamento] FROM [Departamentos]"></asp:SqlDataSource>
</HeaderTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("NomeDepartamento") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("NomeDepartamento") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DataPedido" HeaderText="Data" DataFormatString = "{0:dd, MMM yyyy}" SortExpression="DataPedido" />
<asp:BoundField DataField="DataFinalizado" HeaderText="Finalizado a" DataFormatString = "{0:dd, MMM yyyy}" SortExpression="DataFinalizado" />
<asp:BoundField DataField="Nome" HeaderText="Nome" SortExpression="Nome" />
<asp:BoundField DataField="Estado" HeaderText="Estado" SortExpression="Estado" Visible="False" />
<asp:BoundField DataField="IdPedido" HeaderText="IdPedido" InsertVisible="False" ReadOnly="True" SortExpression="IdPedido" Visible="False" />
</Columns>
</asp:GridView>
THe problem in your Row.Cells(3).Text is that you are defining the ItemTemplate in your gridview with Label and to get the ItemTemplates value you have to first find the control and then get the value from that control.
If you want the value of the label then use the following code to get the value,
Label label = (Label)Row.Cells(3).FindControl("Label1");
if(label != null)
string depar = label.Text;
NOTE
Code is in the c# you might want to convert it to the VB.

Why am I not getting any data back when I click on ImageButton in a GridView

I have the following Gridview, with an ImageButton in the last column. I am trying to return the First and Last names from the row from which the button has been clicked. I have spent several hours looking on here and other sites trying to get it to work, but with no success.
If someone could have a look at my code and see if I am doing anything wrong it would be much appreciated.
Thanks
ASP Code
<asp:GridView runat="server" ID="gvSecondaryContacts" AutoGenerateColumns="False" DataKeyNames="ContactID" ShowHeaderWhenEmpty="false" GridLines="None" OnRowCommand="gvSecondaryContacts_OnRowCommand" >
<Columns>
<asp:BoundField DataField="ContactID" HeaderText="ContactID" InsertVisible="False" ReadOnly="True" SortExpression="ContactID" Visible="false"/>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("FirstName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtSecFirstName" Text='<%# Eval("FirstName") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("LastName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtSecLastName" Text='<%# Eval("LastName") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("Email") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtSecEmail" Text='<%# Eval("Email") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Position">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("ClubPosition") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtSecClubPosition" Text='<%# Eval("ClubPosition") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton runat="server" ID="ibtnDelete" CommandName="Delete" AlternateText="Delete Contact" CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
VB Code
Public Sub gvSecondaryContacts_OnRowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
If e.CommandName = "Delete" Then
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
Dim row = gvSecondaryContacts.Rows(index)
Dim ContactID As Integer = Convert.ToInt32(gvSecondaryContacts.DataKeys(index).Value)
Dim sFirstName As String = gvSecondaryContacts.Rows(index).Cells(1).Text
Dim sLastName As String = gvSecondaryContacts.Rows(index).Cells(2).Text
MsgBox("Your name is " & sFirstName & " " & sLastName)
End If
End Sub
I have also tried the following for the ImageButton but it returned is a type and cannot be used as an expression error
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton runat="server" ID="ibtnDelete" CommandName="Delete" AlternateText="Delete Contact" CommandArgument="<%# CType(Container, GridViewRow).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
You could hanlde the click-event instead. You can cast the ImageButon's NamingContainer to GridViewRow in the click-event handler. Then you just have to use FindControl:
Protected Sub Delete(sender As Object, e As EventArgs)
Dim ctrl = DirectCast(sender, Control)
Dim row = DirectCast(ctrl.NamingContainer, GridViewRow)
' you should rename this to LblFirstName
Dim Label2 = DirectCast(row.FindControl("Label2"), Label)
' you should rename this to LblLastName
Dim Label1 = DirectCast(row.FindControl("Label1"), Label)
'MessageBoxes in ASP.NET don't make much sense
MsgBox("Your name is " & Label2.Text & " " & Label1.Text)
End Sub
I think the problem is setting CommandArgument of ImageButton
CommandArgument="<%# CType(Container, GridViewRow).RowIndex %>"
You don't have do it according to this MSDN Example. Also you (if data binding done from server side) should bind your gridview only if page is not posting back as;
If Not Page.IsPostBack Then
'Bind your gridview here
End if
try this
Dim sFirstName As String = ((Label)gvSecondaryContacts.Rows(index).Cells(1).FindControl("Label2")).Text
Dim sLastName As String =((Label)gvSecondaryContacts.Rows(index).Cells(2).FindControl("Label1")).Text

Need variable number of drop-down lists in a gridview template field

I have the following gridview defined which is populating perfectly:
<asp:GridView runat="server" ID="chargeDetail" AutoGenerateColumns="false" DataKeyNames="LineItemNumber,DetailId,IsParking" CellSpacing="0" CellPadding="6"
HorizontalAlign="Center" EnableViewState="true" ShowFooter="true">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="Student ID" ReadOnly="True" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="StudentName" HeaderText="Name" ReadOnly="true" />
<asp:BoundField DataField="CampusName" HeaderText="Campus" ReadOnly="true" />
<asp:TemplateField HeaderText="Description" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label runat="server" ID="LineItemDetailLabel" Text='<%# IIf(Eval("Mandatory") = "1", Eval("LineItemDetail") + " *", Eval("LineItemDetail")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Cost" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
$<asp:Label runat="server" ID="LineItemCostLabel" Text='<%# Eval("LineItemCost") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Options" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label runat="server" ID="lblOptionsAvailable"
Text='<%# IIf(Eval("AttributesAvailable") = "1", "Options will be available to select on the next screen.", "No options available.") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Pay Now" ItemStyle-HorizontalAlign="Center" FooterText="Total:">
<ItemTemplate>
<asp:Checkbox runat="server" ID="cbLineItemSelected" Checked='<%# IIf(Eval("Selected") = "1", "True", "False") %>'
Enabled='<%# IIf(Eval("Mandatory") = "1", "False", "True") %>' AutoPostBack="True" OnCheckedChanged="cbLineItemSelected_CheckedChanged" />
</ItemTemplate>
<FooterStyle Font-Bold="True" HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
$<asp:Label runat="server" ID="lblLineTotalCost" Text='<%# IIf(Eval("Selected") = "1", Eval("LineItemCost"), "0.00") %>' />
</ItemTemplate>
<FooterTemplate>
$<asp:Label runat="server" ID="lblTotal" />
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
</Columns>
</asp:GridView>
In the TemplateField where HeaderText="Options", I need to be able to create a variable number of drop-down lists. For each fee the school may be charging, they could have any number of attributes associated. For example, a TShirt fee may need to collect Size and Color and each attribute may have multiple options.
Right now, you can see I have a label that is populating correctly but I need to be able to create the two drop-down lists, in this case for Size and Color, so the parent can specify them when they check the box to include this fee in their charges. You'll notice that in the Pay Now column, the checkbox has an OnCheckedChanged event which currently updates the total column and overall total in the footer row.
I would ideally like that event to populate the drop-downs when it is checked so the parent can make their selections. I'll also need to know how to handle the post back from those drop-downs so I can get the selections recorded correctly.
From what I can find, I'm guessing I need to create a nested gridview where I can put the drop-downlists but I can't find any examples to point me in the right direction of how to make that work. I can easily populate the drop-downs from the code behind and if pointed in the right direction, access the data as the parents enter it. Just need a bit of direction or an easier way.
Thanks in advance!
OK, I came up with a solution that seems to work. Inside the gridview definition, I nested another gridview with the drop-down list inside of it as follows:
<asp:TemplateField HeaderText="Options" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:GridView runat="server" ID="gvOptions" AutoGenerateColumns="False" DataKeyNames="AttributeId" HorizontalAlign="center" EnableViewState="true"
GridLines="None" EmptyDataText="No available options." ShowHeader="False">
<Columns>
<asp:BoundField DataField="Description" ReadOnly="true" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlOptionSelection" DataTextField="Description" DataValueField="OptionId"
EnableViewState="true" AutoPostBack="true" OnSelectedIndexChanged="ddlOptionSelection_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
The challenge was figuring out how to tie everything together since data in the nested gridview relied on data keys from the parent gridview. The RowDataBound event for the parent finds the child gridview and populates the dropdowns as follows (gvOptions is the child and chargeDetail is the parent):
Protected Sub chargeDetail_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles chargeDetail.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim gv As GridView = DirectCast(e.Row.FindControl("gvOptions"), GridView)
Dim cb As CheckBox = DirectCast(e.Row.FindControl("cbLineItemSelected"), CheckBox)
Dim lineItem As String = chargeDetail.DataKeys(e.Row.RowIndex).Values("LineItemNumber")
gv.DataSource = GetOptions(chargeDetail.DataKeys(e.Row.RowIndex).Values("DetailId"))
gv.DataBind()
Dim gridLineCount As Integer = gv.Rows.Count()
Dim gridWorkingRow As Integer
For gridWorkingRow = 0 To gridLineCount - 1
Dim ddl As DropDownList = gv.Rows(gridWorkingRow).FindControl("ddlOptionSelection")
Dim AttribId As Integer = gv.DataKeys(gridWorkingRow).Values("AttributeId")
ddl.DataSource = PopulateOptions(AttribId)
ddl.DataBind()
ddl.SelectedValue = GetSelectedValue(AttribId, lineItem)
If cb.Checked Then
ddl.Enabled = True
Else
ddl.Enabled = False
End If
Next gridWorkingRow
End If
End Sub
When one of the dropdowns change, the following is fired. I found it easier, based on how the data is stored in the database, to re-send all of the options since the attribute:option pairs are concatenated to be stored in a single field:
Protected Sub ddlOptionSelection_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim ddlSender As DropDownList = DirectCast(sender, DropDownList)
Dim row As GridViewRow = DirectCast(ddlSender.NamingContainer, GridViewRow)
Dim gvOption As GridView = DirectCast(row.NamingContainer, GridView)
Dim chargeDetailRow As GridViewRow = DirectCast(gvOption.Parent.Parent, GridViewRow)
Dim LineItemNumber As Integer = CInt(chargeDetail.DataKeys(chargeDetailRow.RowIndex).Values("LineItemNumber"))
Dim gridLineCount As Integer = gvOption.Rows.Count()
Dim gridWorkingRow As Integer
Dim OptionString As String = ""
For gridWorkingRow = 0 To gridLineCount - 1
Dim ddl As DropDownList = gvOption.Rows(gridWorkingRow).FindControl("ddlOptionSelection")
Dim AttribId As String = gvOption.DataKeys(gridWorkingRow).Values("AttributeId")
If gridWorkingRow = gridLineCount - 1 Then
OptionString = OptionString + AttribId + ":" + ddl.SelectedValue
Else
OptionString = OptionString + AttribId + ":" + ddl.SelectedValue + ","
End If
Next gridWorkingRow
Dim PortalConn As New SqlConnection
PortalConn.ConnectionString = ConfigurationManager.ConnectionStrings("PortalConnStr").ConnectionString
PortalConn.Open()
Dim WriteBackSQL As New SqlCommand("sp_schedulePickup_UpdateOption", PortalConn)
WriteBackSQL.CommandType = Data.CommandType.StoredProcedure
WriteBackSQL.Parameters.Add(New SqlParameter("#SessionID", Session.SessionID.ToString()))
WriteBackSQL.Parameters.Add(New SqlParameter("#LineItemNumber", LineItemNumber))
WriteBackSQL.Parameters.Add(New SqlParameter("#Option", OptionString))
Dim returnStatus As Integer
Dim rsReturn As SqlDataReader = WriteBackSQL.ExecuteReader()
Do While rsReturn.Read()
returnStatus = rsReturn("ReturnStatus")
Loop
rsReturn.Close()
rsReturn = Nothing
PortalConn.Close()
PortalConn = Nothing
chargeDetail.DataSource = GetChargeDetails()
chargeDetail.DataBind()
getTotal()
End Sub

Without using SelectedIndexChanged, how to retrieve value of each row from gridview?

I have a GridView,
without using SelectedIndexChanged, how can I retrieve the value of each row from GridView when click on each button in each row?
this is my aspx code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"
DataSourceID="SqlDataSource1" ShowHeader="False" AllowPaging="True" BorderColor="White"
CellPadding="6" GridLines="None" Height="100px" Width="800px">
<Columns>
<asp:TemplateField>
<ItemTemplate>
Card Name:
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
<br />
Cost :
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Price") %>'></asp:Label>
<br />
<asp:Label ID="Label3" runat="server" Text='<%# Bind("ProductImgID") %>'></asp:Label>
<asp:Image ID="Image3" runat="server" ImageUrl='<%# Eval("ProductImgUrl", "images/{0}") %>' />
<br />
<asp:Button ID="btnAddProduct" runat="server" Text="Add" />
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
One option can be to Bind the CommandArgument of the button to the ProductID
<asp:Button ID="btnAddProduct" runat="server" Text="Add" CommandArgument='<%#Bind("ProductID")%>' />
and then in the RowCommand event retrieve the ProductID and extract the row from database
string prodID=(string)e.CommandArgument()
then using the ID retrieve the row from database.
To get a row value, you have to get the row Reference, After getting the row you can easily get to the specified column and can get the value
Lets Consider you have a "link button control" in a template field column. For the gridview you have to set Row Command Event, and also in the edit template of the column, set a command name for the link button also say "lnkTest"
In RowCommand Event you have to include the following section of code
if(e.CommandName.Equals("lnkTest")) // Checks that link button was clicked
{
GridViewRow grdRow = (((LinkButton)e.CommandSource).Container)
// This Will give you the reference of the Row in which the link button was clicked
int grdRowIndex = grdRow.RowIndex;
//This will give you the index of the row
var uniqueDataKeyValue = GridView1.DataKeys[grdRowIndex].Value;
//This will give you the DataKey Value for the Row in which the link Control was click
Hope the above code will help
Add CommandArgument='<%# Container.DataItemIndex %>' to your Add button
<asp:Button ID="btnAddProduct" runat="server" Text="Add" CommandArgument='<%# Container.DataItemIndex %>'/>
To retrive Name, in gridview row command use this code
Dim gvr As GridViewRow = grvGRNCONs.Rows(e.CommandArgument)
Dim name As String = DirectCast(gvr.FindControl("Label1"), Label).Text
and so on..
<asp:GridView ID="grdResults" CssClass="CommonTable dataTable" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="Sl#">
<ItemTemplate>
<asp:Label ID="lblSlno" Text='<%# Container.DataItemIndex+1 %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="" ControlStyle-Height="15px" ControlStyle-Width="15px">
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" CssClass="PInfoTd" />
<ItemTemplate>
<asp:ImageButton ID="lknassesno" ToolTip="Edit Assessment" Width="50" CssClass="NewButton" ***CommandName="LINK"***
runat="server" ImageUrl="~/img/Edit.png" />
<asp:HiddenField ID="hidassesmentno" Value='<%# EVAL("PAN_CODE")%>' runat="server" />
<asp:HiddenField ID="hidPendStatus" Value='<%# EVAL("Pstatus")%>' runat="server" />
<asp:HiddenField ID="hidIPNO"Value='<%#EVAL("IP_NO")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
**code behind**
Protected Sub grdResults_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grdResults.RowCommand
If **e.CommandName = "LINK"** Then
Dim ctrl As Control = e.CommandSource
Dim grrow As GridViewRow = ctrl.Parent.NamingContainer
'Dim i As Integer = Convert.ToInt16(e.CommandArgument)
'Dim lknassesno As HiddenField = DirectCast(e.CommandSource, ImageButton)
Dim hidAssesmentNo As HiddenField = DirectCast(grdResults.Rows(grrow.RowIndex).FindControl("hidassesmentno"), HiddenField)
Dim lblstatus As HiddenField = DirectCast(grdResults.Rows(grrow.RowIndex).FindControl("hidPendStatus"), HiddenField)
Dim hidIpNo As HiddenField = DirectCast(grdResults.Rows(grrow.RowIndex).FindControl("hidIPNO"), HiddenField)
Dim Assno As String = hidAssesmentNo.Value
Dim Ipno As String = hidIpNo.Value
Dim st As String = ""
If lblstatus.Value = "Pending" Then
st = "E"`enter code here`
ElseIf lblstatus.Value = "Completed" Then
st = "V"
End If
Response.Redirect("Assessment.aspx?PAssNo=" & Assno & "&Mode=" & st & "&IPNO=" & Ipno & "")
End If
End Sub

Resources