ASP.NET Gridview Linkbutton Hiding/Display page load issue - asp.net

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 ?

Related

Need to fill Gridview checkbox attribute from a cell data or database data

Hi guys,
I am not a developer but I always try my best to manage my page coding by myself before bothering anyone and by checking many examples and apply them to my web application, but this time I really surrendered and had to ask.
I have a Gridview where I will be using to update one field which is CHECKBOX.
The gridview has a checkbox control where it's checked attribute need to be True or False based on the Database value.
Values are 1 and 2 only
I wrote the below code to catch the cell label and change the checkbox attribute but it didn't work
Protected Sub Refill_checkbox(ByVal sender As Object, ByVal e As System.EventArgs)
Dim i As Integer
For i = 0 To dg.Rows.Count - 1
Dim Test As String = CType(dg.Rows(i).Cells(3).FindControl("Att_Type"), Label).Text
If CType(dg.Rows(i).Cells(4).FindControl("Att_Type"), Label).Text = 1 Then
CType(dg.Rows(i).Cells(6).FindControl("CheckBox_Attendance"), CheckBox).Checked = True
Else
CType(dg.Rows(i).Cells(6).FindControl("CheckBox_Attendance"), CheckBox).Checked = False
End If
Response.Write(Test)
Next
End Sub
Unfortunately it even did not write the Test Variable to find if it catches the label from the gridview or not.
My Gridview is as following:
<asp:GridView ID="dg" runat="server" BorderColor="#CCCCCC" BorderStyle="None" AutoGenerateColumns="False"
BorderWidth="1px" CellPadding="4"
EnableModelValidation="True" ForeColor="Black" GridLines="Horizontal"
Width="99%" AllowPaging="True" PageSize="500" DataSourceID="SqlDataSource_BCS" >
<Columns>
<asp:TemplateField HeaderText="#">
<ItemTemplate>
<%#Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Att_ID" HeaderText="Att_ID"
SortExpression="Att_ID" />
<asp:BoundField DataField="Emp_FullName" HeaderText="Emp_FullName"
SortExpression="Emp_FullName" />
<asp:BoundField DataField="Att_Desc" HeaderText="Att_Desc"
SortExpression="Att_Desc" />
<asp:BoundField DataField="Att_Type" HeaderText="Att_Type"
SortExpression="Att_Type" />
<asp:BoundField DataField="Att_Date" HeaderText="Att_Date"
SortExpression="Att_Date" />
<asp:templatefield HeaderText="Attendance" >
<itemtemplate >
<asp:CheckBox ID="CheckBox_Attendance" runat="server" />
</itemtemplate>
<itemstyle horizontalalign="left" />
</asp:templatefield>
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="White" Font-Bold="True" BorderWidth="0px"/>
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BorderStyle="None" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
</asp:GridView>
I have no idea what is the correct way to do this.
Thanks in advance
You can bind your checkbox directly to the field like so...
<asp:CheckBox ID="CheckBox_Attendance" runat="server" Checked='<%# Eval("Att_type").ToString() = "1" %>' />
Otherwise, handle it directly on your gridview rowdatabound event:
Put the following on your gridview:
<asp:GridView ... OnRowDatabound="dg_RowDataBound">
Change your TemplateField to look like this:
<asp:TemplateField HeaderText="Attendance">
<ItemTemplate>
<asp:HiddenField id="hfType" Value='<%# Eval("Att_Type") %>' />
<asp:CheckBox ID="CheckBox_Attendance" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="left" />
</asp:TemplateField>
In your code behind
Protected Sub dg_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Dim cbAttendance As Checkbox = e.Row.FindControl("CheckBox_Attendance")
Dim hfType as Hiddenfield = e.Row.FindControl("hfType")
If hfType.Value = "1" Then
cbAttendance.Checked = True
End Sub

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.

retrieve data from gridview row to an asp.net form

I would like to retrieve a row from the gridview by clicking on ImageButton (Booking):
here is the code of my grid view:
<asp:GridView ID="GridView1" runat="server" Height="150px" Width="284px"
CssClass="tb" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField HeaderText=" Booking">
<ItemTemplate>
<asp:ImageButton ID="booking" runat="server" HeaderText="Booking" ImageUrl="booking_icon.ico" PostBackUrl="form.aspx"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Trade" HeaderText="Trade" SortExpression="Trade" />
<asp:BoundField DataField="CARRIER" HeaderText="CARRIER"
SortExpression="CARRIER" />
</Columns>
</asp:GridView>
The textbox of the form.aspx page that should be filed from the gridview row:
<asp:TextBox ID="trade" runat="server" CssClass="input , focus"></asp:TextBox>
<asp:TextBox ID="carrier" runat="server" CssClass="input , focus"></asp:TextBox>
Add GridView RowCommand event and command argument for image button where you can pass an id or something to determine the current row.
<asp:GridView onrowcommand="gvRowCommand" ID="GridView1" runat="server" Height="150px" Width="284px"
CssClass="tb" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<ItemTemplate>
<asp:ImageButton CommandArgument='<%# Eval("SomeId") %>' ID="booking" runat="server" HeaderText="Booking" ImageUrl="booking_icon.ico" />
</ItemTemplate>
C#
protected void gvRowCommand(object sender, GridViewCommandEventArgs e)
{
var someId = e.CommandArgument;
}
VB.Net
Protected Sub gvRowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand
Dim someId As Integer = Convert.ToInt32(e.CommandArgument)
End Sub
You can refer msdn for more : http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx

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

ASP.NET (VB): GridView with ImageButton > Populate text box with comments

It has been so long since I have coded a page in VB. For the life of me I just cannot remember how to do this.
I have a GridView on an ASP page. Each row has a comment ImageButton. I already have the gridview and text box wrapped in a UpdatePanel. The gridview shows all of the correct information. I just need to add some code to populate the text box with the comment when a user clicks on that row's ImageButton.
The comments are stored in SQL 2005 DB if that makes a difference. Should I shove the comments inside a hidden field of the gridview or is there a function that will allow me to query the db for that specific comment.
End goal would be to not refresh the page if possible.
Your help is greatly appreciated to help me get over this writer's block!
OK, you could do this either way, with a HiddenField or by looking up in the DB.
HiddenField
In the ItemTemplate that contains the ImageButton, add CommandName and CommandArgument attributes to the ImageButton, and a HiddenField that is bound to the comment field from the database:
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:ImageButton ID="btnComment" runat="server" ImageUrl="images/comment.gif" CommandName="SelectComment" CommandArgument='<%# Container.DataItemIndex %>' />
<asp:HiddenField runat="server" id="CommentHiddenField" Value='<%# Eval("Comment") %>' />
</ItemTemplate>
</asp:TemplateField>
In the code-behind, add a method for handling the RowCommand event for the GridView:
Private Sub Gridview2_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles Gridview2.RowCommand
Dim rowIndex As Integer
Dim commentHiddenField As HiddenField
If e.CommandName = "SelectComment" Then
rowIndex = Integer.Parse(e.CommandArgument.ToString)
commentHiddenField = DirectCast(Gridview1.Rows(rowIndex).Cells(5).FindControl("CommentHiddenField"), HiddenField)
txtComments.Text = commentHiddenField.Value
End If
End Sub
DB Lookup
Add the attributes to the ImageButton:
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:ImageButton ID="btnComment" runat="server" ImageUrl="images/comment.gif" CommandName="SelectComment" CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
In the code-behind, add a method for handling the RowCommand event for the GridView:
Private Sub Gridview2_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles Gridview2.RowCommand
Dim rowIndex As Integer
Dim key As String
rowIndex = Integer.Parse(e.CommandArgument.ToString)
key = Gridview1.DataKeys(rowIndex).Value.ToString
txtComments.Text = GetCommentFromDB(key)
End Sub
Here is the markup...
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<tr class="dvrow" align="center">
<td style="text-align:left;" colspan="2">History<br />
<div id="div1" style="width:600px;">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
GridLines="None" DataKeyNames="RepIssueHistoryID"
DataSourceID="sqlIssueHistory" Width="600px" AllowSorting="True"
AllowPaging="True" CssClass="grid" RowStyle-Height="15px">
<PagerStyle CssClass="footer" />
<Columns>
<asp:TemplateField HeaderText="Mail">
<ItemTemplate>
<asp:CheckBox ID="chkMailComment" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="RepIssueStatus" SortExpression="RepIssueStatus"
HeaderText="Status" ItemStyle-Width="120px" >
<ItemStyle Width="120px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="RepIssuePriority" SortExpression="RepIssuePriority"
HeaderText="Priority" ItemStyle-Width="100px" >
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="User" SortExpression="User" HeaderText="Rep"
ItemStyle-Width="180px" >
<ItemStyle Width="180px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="DateUpdate" SortExpression="DateUpdate"
HeaderText="Date" ItemStyle-Width="200px" >
<ItemStyle Width="200px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:ImageButton ID="btnComment" runat="server" ImageUrl="images/comment.gif" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Attachment">
<ItemTemplate>
<asp:ImageButton ID="btnAttachment" runat="server" ImageUrl="images/folder.gif" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No history currently exists.<br />
</EmptyDataTemplate>
<RowStyle Height="15px"></RowStyle>
<EmptyDataRowStyle CssClass="empty" />
</asp:GridView>
</div>
</td>
</tr>
<tr class="dvrow" align="center">
<td style="text-align:left;" colspan="2">Rep Comment<br />
<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine"
Width="600px" Height="180px" ReadOnly="true" />
</td>
</tr>
</ContentTemplate>
</asp:UpdatePanel>
So the basic idea would be for someone to click on btnComment on whichever row and that comment would then show up in txtComment. Hope that explains it better.

Resources