Execute an "INSERT INTO" in the HeaderRow using RowCommand - asp.net

I am trying to execute an "INSERT INTO" in the HeaderRow.
The button in the HeaderRow does not trigger the RowCommand.
The gridview contains 5 columns: idt, datetime, col1, col2 and col3.
Protected Sub gvtest_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs) Handles gvtest.RowCommand
Dim txt1, txt2, txt3 as String
If e.CommandName = "insertinto" Then
Try
txt1 = DirectCast(gvtest.HeaderRow.FindControl("tbins1"), TextBox).Text
txt2 = DirectCast(gvtest.HeaderRow.FindControl("tbins2"), TextBox).Text
txt3 = DirectCast(gvtest.HeaderRow.FindControl("tbins3"), TextBox).Text
sqltest.InsertParameters("#datetime").DefaultValue = DateTime.Now()
sqltest.InsertParameters("#col1").DefaultValue = txt1
sqltest.InsertParameters("#col2").DefaultValue = txt2
sqltest.InsertParameters("#col3").DefaultValue = txt3
sqltest.Insert()
Catch ex As Exception
TextBox1.Text = "Insert: " & ex.Message
End Try
gvtest.DataBind()
End If
End Sub
default.aspx
<asp:GridView ID="gvtest"
runat="server"
DataSourceID="sqltest"
AutoGenerateColumns="False"
DataKeyNames="idt"
OnRowCommand="gvtest_RowCommand">
<Columns>
<asp:BoundField DataField="idt" HeaderText="idt" Readonly="true" SortExpression="idt" />
<asp:BoundField DataField="datetime" HeaderText="datetime" SortExpression="datetime" />
<asp:TemplateField SortExpression="col1">
<HeaderTemplate>
<asp:TextBox ID="tbins1" text="col1" runat="server" MaxLength="40" />
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="col2">
<HeaderTemplate>
<asp:TextBox ID="tbins2" text="col2" runat="server" MaxLength="40" />
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="col3">
<HeaderTemplate>
<asp:TextBox ID="tbins3" text="col3" runat="server" MaxLength="40" />
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Button ID="btnins" CommandName="insertinto" runat="server" Text="Insert Into" OnClick="btnins_Click" />
</HeaderTemplate>
</asp:GridView>
<asp:SqlDataSource
id="sqltest"
ConnectionString="<%$ ConnectionStrings:connone %>"
SelectCommand="SELECT * FROM [test];
InsertCommand="INSERT INTO [test] datetime,col1,col2,col3 VALUES #datetime,#col1,#col2,#col3;">
</asp:SqlDataSource>
Note for brevity textboxes were omitted containing the gridview data.

You need to use a known command name, like Insert. It will not know your custom command name.
Read this:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.buttonfield.commandname(v=vs.110).aspx
change:
<asp:Button ID="btnins" CommandName="insertinto" runat="server" Text="Insert Into" OnClick="btnins_Click" />
to:
<asp:Button ID="btnins" CommandName="Insert" runat="server" Text="Insert Into" OnClick="btnins_Click" />

GridView row command events come from the Command controls on the data rows.
You placed a button in the GridView header, you need to process the btnins.Command event

Related

FindControl throwing NullReferenceException

Within my ASP gridview, I have the following (updated to show full gridview):
<asp:GridView ID="TPAnnuity_GridView" AllowSorting="true" AllowPaging="true" Runat="server"
DataSourceID="TPAnnuity_SqlDataSource" DataKeyNames="AnnuityTotalPointsID"
AutoGenerateColumns="False" ShowFooter="true" PageSize="20">
<Columns>
<asp:TemplateField HeaderText="Company" SortExpression="CompanyName" HeaderStyle-VerticalAlign="Bottom">
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("CompanyName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="EditACompanyID" runat="server" DataSource="<%# ddlCompanyDS %>" DataValueField="CompanyID" DataTextField="CompanyName" selectedValue='<%# Bind("CompanyID") %>'></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="NewCompanyID" runat="server" DataSource="<%# ddlCompanyDS %>" DataValueField="CompanyID" DataTextField="CompanyName"></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ControlToValidate="NewCompanyID" Display="Dynamic" ForeColor="" ErrorMessage="You must enter a value. *" Enabled="false"></asp:RequiredFieldValidator>
</FooterTemplate>
<FooterStyle Wrap="False" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<br />
<i>No Commission Data to display.</i>
<br />
<br />
</EmptyDataTemplate>
</asp:GridView>
And within my back end, I have the following:
Sub TPAnnuity_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles TPAnnuity_GridView.RowCommand
If e.CommandName = "Cancel" Then
'Reset Footer Row input fields
CType(TPAnnuity_GridView.FooterRow.FindControl("NewCompanyID"), DropDownList).SelectedIndex = 0
ElseIf e.CommandName = "Insert" Then
TPAnnuity_SqlDataSource.InsertParameters.Clear()
Dim test1 As New Parameter("CompanyIDInt", TypeCode.Int32)
test1.DefaultValue = CType(TPAnnuity_GridView.FooterRow.FindControl("NewCompanyID"), DropDownList).SelectedValue
TPAnnuity_SqlDataSource.InsertParameters.Add(test1)
TPAnnuity_SqlDataSource.Insert()
ElseIf e.CommandName = "Update" Then
TPAnnuity_SqlDataSource.UpdateParameters.Clear()
Dim param1 As New Parameter("CompanyIDInt", TypeCode.Int32)
param1.DefaultValue = CType(TPAnnuity_GridView.FooterRow.FindControl("EditACompanyID"), DropDownList).SelectedValue ****THIS IS THE PROBLEM LINE****
TPAnnuity_SqlDataSource.UpdateParameters.Add(param1)
TPAnnuity_SqlDataSource.Update()
End If
End Sub
The Cancel and Insert functions work just fine, operating off of the footer. Every time hit the "Update" button, I get a NullReferenceException on the param1.Default Value = line.
Can anyone help me figure out what's going on here?
Your row should look like this:
param1.DefaultValue = CType(e.CommandSource.FindControl("EditACompanyID"), DropDownList).SelectedValue
Instead of utilizing the FooterRow, you have to use the source row. Since you passed that in with e, you can use this.

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.

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

CollapsiblePanelExtender in nested Repeater and Gridview setup doesn't function

I have a setup using three levels of nesting: A Repeater, the items of which utilize CollapsiblePanelExtenders (which work), and each contain a GridView. Each of these then contain another GridView which is controlled by another CollapsiblePanelExtender. These inner CollapsiblePanels will effectively show either an expanded or collapsed state only if I set clientState to True. However, they do not effectively expand or collapse as expected. Everything is bound dynamically.
Here is the markup...
<asp:Repeater ID="cat_repeater" runat="server">
<ItemTemplate>
<asp:CollapsiblePanelExtender id="cat_cpExt" runat="server" TargetControlID="cat_pnl" CollapsedSize="0" Collapsed="false" CollapsedImage="collapsed.png" ExpandedImage="expanded.png" ExpandControlID="cpControl_pnl" CollapseControlID="cpControl_pnl" TextLabelID="cpControl_lbl" ImageControlID="cpControl_img" CollapsedText='<%#configCPText(eval("Title"), False)%>' ExpandedText='<%#configCPText(eval("Title"), True) %>' />
<asp:Panel ID="cpControl_pnl" runat="server" Visible='<%#itemVisible(eval("ID"), "Recipients", "CategoryID") %>' CssClass="CPanelStyle">
<asp:Image ID="cpControl_img" runat="server" ImageUrl="expanded.png" />
<asp:Label ID="cpControl_lbl" runat="server" Text='<%#configCPText(eval("Title"), True) %>' CssClass="CPanelText" />
</asp:Panel>
<asp:Panel ID="cat_pnl" runat="server">
<asp:GridView ID="recipients_gv" runat="server" CssClass="GVStyle" HeaderStyle-CssClass="GVHeaderStyle" RowStyle-CssClass="GVItemStyle" AutoGenerateColumns="false" GridLines="none" AllowPaging="false">
<Columns>
<asp:TemplateField HeaderText="Name" SortExpression="Last Name" ItemStyle-CssClass="GVNameStyle">
<ItemTemplate>
<asp:Literal id="name_lit" runat="server" text='<%#formatNameText(eval("FirstName"), eval("LastName")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gifts" ItemStyle-Width="500px">
<ItemTemplate>
<asp:CollapsiblePanelExtender id="gifts_cpExt" runat="server" TargetControlID="gifts_pnl" CollapsedSize="0" Collapsed="true" CollapsedImage="collapsed.png" ExpandedImage="expanded.png" ExpandControlID="cpControl_pnl2" CollapseControlID="cpControl_pnl2" TextLabelID="cpControl_lbl2" ImageControlID="cpControl_img2" CollapsedText='<%#configGiftsCPText(eval("ID"), True)%>' ExpandedText='<%#configGiftsCPText(eval("ID"), False) %>' />
<asp:Panel ID="cpControl_pnl2" runat="server" Visible='<%#itemVisible(eval("ID"), "Gifts", "RecipientID") %>'>
<asp:Image ID="cpControl_img2" runat="server" ImageUrl="collapsed.png" />
<asp:Label ID="cpControl_lbl2" runat="server" Text='<%#configGiftsCPText(eval("ID"), False) %>' />
</asp:Panel>
<asp:Panel ID="gifts_pnl" runat="server">
<asp:GridView ID="gifts_gv" runat="server" DataKeyNames="ID" RowStyle-CssClass="GVInnerItemStyle" HeaderStyle-CssClass="GVInnerHeaderStyle" Gridlines="None" AutoGenerateColumns="false" AllowPaging="false" Width="475px">
<Columns>
<asp:TemplateField ItemStyle-CssClass="GVInnerButtonItemStyle" HeaderText="Description">
<ItemTemplate>
<asp:LinkButton ID="gift_lBtn" runat="server" Text='<%#eval("Description") %>' CommandName="Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Complete" ItemStyle-Width="50px">
<ItemTemplate>
<asp:CheckBox ID="giftComplete_cbx" runat="server" Checked='<%#eval("Complete") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
<br />
</ItemTemplate>
</asp:Repeater>
...And here is the code to bind everything:
Protected Sub bindCategories()
Try
oCmd.Connection = oConn
oCmd.CommandType = CommandType.Text
strSQL = "SELECT * FROM Categories"
oCmd.CommandText = strSQL
oDA.SelectCommand = oCmd
oDA.Fill(oDTbl)
cat_repeater.DataSource = oDTbl
cat_repeater.DataBind()
For i As Integer = 0 To oDTbl.Rows.Count - 1
oCmd.Parameters.Clear()
inner_dTbl.Clear()
strSQL = "SELECT *, Title FROM Recipients INNER JOIN Categories on Recipients.CategoryID = Categories.ID WHERE CategoryID = #CategoryID ORDER BY LastName"
oParam = New SqlParameter
oParam.ParameterName = "CategoryID"
oParam.SqlDbType = SqlDbType.Int
oParam.Value = oDTbl.Rows(i)("ID")
oCmd.Parameters.Add(oParam)
oCmd.CommandText = strSQL
oDA.SelectCommand = oCmd
oDA.Fill(inner_dTbl)
Dim gv As GridView = CType(cat_repeater.Items(i).FindControl("recipients_gv"), GridView)
gv.DataSource = inner_dTbl
gv.DataBind()
For j As Integer = 0 To inner_dTbl.Rows.Count - 1
oCmd.Parameters.Clear()
gifts_dTbl.Clear()
strSQL = "SELECT * FROM Gifts WHERE RecipientID = #RecipientID ORDER BY Description"
oParam = New SqlParameter
oParam.ParameterName = "RecipientID"
oParam.SqlDbType = SqlDbType.Int
oParam.Value = inner_dTbl.Rows(j)("ID")
oCmd.Parameters.Add(oParam)
oCmd.CommandText = strSQL
oDA.SelectCommand = oCmd
oDA.Fill(gifts_dTbl)
Dim inner_gv As GridView = CType(gv.Rows(j).FindControl("gifts_gv"), GridView)
inner_gv.DataSource = gifts_dTbl
inner_gv.DataBind()
Dim cpExt As CollapsiblePanelExtender = CType(gv.Rows(j).FindControl("gifts_cpExt"), CollapsiblePanelExtender)
cpExt.Collapsed = True
cpExt.ClientState = True
Next
Next
Catch ex As Exception
Throw ex
End Try
End Sub
I've successfully used CollapsiblePanelExtenders in a 2-level nested GridView setup that without a problem before, and without having to set clientState. However, I've had to specify clientState when using CollapsiblePanelExtenders with Repeaters before.
Does anyone have any input regarding why these extenders will not function in this 3-level nested setup?
It looks like the reason it's required is because it needs a postback to make all that logic work:
if (this.SupportsClientState) {
ScriptManager.RegisterHiddenField(this, this.ClientStateFieldID, this.SaveClientState());
this.Page.RegisterRequiresPostBack(this);
}
This is from public class ScriptControlBase in the AjaxControlToolkit space.
Are you wrapping this in an UpdatePanel? Does it cause a postback to use the CPE in the repeater? It's been awhile since I've tried to do a CPE in a repeater, and I'm not setup at this point to check the code out and build one.
Is there a reason you can't just use something completely client-side and just expand/collapse these using javascript? Are you loading data dynamically server side when these things get expanded?

ASP.NET Gridview Linkbutton Hiding/Display page load issue

I am trying to hide/display a linkbutton in my gridview based on wether not the row in the Gridview is part of my shopping cart.
This is the gridview
<asp:GridView ID="productListTable" runat="server" DataSourceID="srcProductListPerCustomer" AutoGenerateColumns="False" AlternatingRowStyle-CssClass="tr_dark" HeaderStyle-CssClass="header_req" BorderWidth="0px" GridLines="None" AllowPaging="true" PageSize="25" EmptyDataText="No records." AllowSorting="false" Width="100%" DataKeyNames="product_ID_key" OnRowDataBound="productListTable_RowDataBound" OnRowCommand="productListTable_RowCommand" >
<Columns>
<asp:TemplateField HeaderText="Product Name" HeaderStyle-Width="250px" SortExpression="productName" ItemStyle-CssClass="product_name" >
<ItemTemplate>
<asp:Label ID="ProductNameField" runat="server" Text='<%# Eval("productName").ToString() %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<Columns>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtQuantity" Columns="5"></asp:TextBox><br />
<asp:LinkButton runat="server" ID="btnRemove" Text="Remove" CommandName="Remove" CommandArgument='<%# Eval("product_ID_key") %>' style="font-size:12px;" Visible="false"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="header_req" />
<AlternatingRowStyle CssClass="tr_dark" />
<PagerStyle CssClass="pagination" />
<PagerSettings PageButtonCount="3" FirstPageText="First" LastPageText="Last" NextPageText="Next" PreviousPageText="Previous" Mode="NumericFirstLast" />
</asp:GridView>
The way I am trying to do this at the moment is by row data bound
Protected Sub productListTable_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles productListTable.RowDataBound
' If we are binding the footer row, let's add in our total
If e.Row.RowType = DataControlRowType.DataRow Then
'e.Row.Cells(6).Text = "Total Price: " & ShoppingCart.Instance.GetSubTotal().ToString("C")
Dim productId = Convert.ToInt32(productListTable.DataKeys(e.Row.RowIndex).Value)
Dim txtQuantity As TextBox = CType(e.Row.Cells(1).FindControl("txtQuantity"), TextBox)
Dim removeButton As LinkButton = CType(e.Row.Cells(1).FindControl("btnRemove"), LinkButton)
Dim updatedItem = New CartItem(productId)
For Each item As CartItem In ShoppingCart.Instance.Items
If item.Equals(updatedItem) Then
txtQuantity.Text = item.Quantity
removeButton.Visible = True
End If
Next
End If
End Sub
And it works fine, but not at the initial refresh of the page when adding a new product but only after a hard refresh I see the button appear. Do I need to perform this check in a different lifecycle or gridview event so i can see the update immediately ?

Resources