Gridview button onclick not firing from a Microsoft Developer Network Example - asp.net

I created a simple Grid view with Multiple columns and add a button so when clicked pass the values of the row to a different webform but button on click not firing. I use the example code from the link
: http://msdn.microsoft.com/en-us/library/bb907626(v=vs.100).aspx
And this is my code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource1"
PageSize="100" AutoGenerateColumns="False">
<Columns>
<%--<asp:HyperLinkField HeaderText="Edit" NavigateUrl="FormReport2.aspx"
Text="Edit" />--%>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="fldEmployeeID" HeaderText="EmployeeID"
SortExpression="fldEmployeeID" />
<asp:BoundField DataField="fldAbsentDate" HeaderText="AbsentDate"
SortExpression="fldAbsentDate" />
<asp:BoundField DataField="fldAbsentCode" HeaderText="AbsentCode"
SortExpression="fldAbsentCode" />
<asp:BoundField DataField="fldRuleViolationWarningType"
HeaderText="Rule Violation Warning Type"
SortExpression="fldRuleViolationWarningType" />
<asp:BoundField DataField="fldRuleViolationIssueDate"
HeaderText="Rule Violation Issue Date"
SortExpression="fldRuleViolationIssueDate" />
<asp:BoundField DataField="fldLOAEndDate" HeaderText="LOA End Date"
SortExpression="fldLOAEndDate" />
</Columns>
</asp:GridView>
code behind
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "AddToCart") Then
' Retrieve the row index stored in the CommandArgument property.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button
' from the Rows collection.
Dim row As GridViewRow = GridView1.Rows(index)
' Add code here to add the item to the shopping cart.
End If
End Sub
Any help would be very appreciated. And also what would be the best way to pass the values from the row to a different web form from the code behind?

You forgot to sing up for the event. See the last line here:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource1"
PageSize="100" AutoGenerateColumns="False"
OnRowCommand="GridView1_RowCommand">

Related

How to make check boxes checked on a Grid view when one checkbox of a row is checked?

I have a gridview. Which consisits of two checkbox item templates.
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None"
<Columns>
<asp:BoundField DataField="student_name" HeaderText="Student Name" SortExpression="student_name" >
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="student_id"
HeaderText="Student ID" ItemStyle-HorizontalAlign="Center"
SortExpression="student_id" ReadOnly="True" >
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Practical Test">
<ItemTemplate>
<asp:CheckBox AutoPostBack="false" Checked="true" Id="CheckBoxTheory" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Theory Test">
<ItemTemplate>
<asp:CheckBox AutoPostBack="false" Checked="true" Id="CheckBoxPractical" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
When checking any one of the checkbox of a row of grid view ,i wants to make check the other checkbox automatically..and vice versa.. how is it possible?
On server side you need to change the checkbox so it has AutoPostBack="True" and add a OnCheckedChanged="CheckBoxTheory_Checked" so that the system can postback when you select it.
Then you can use something along the lines of:
Sub CheckBoxTheory_Checked (sender as object, e as eventargs)
Dim CheckBoxTheory as CheckBox = sender
Dim gvRow as GridviewRow = DirectCast(CheckBoxTheory.NamingContainer, GridviewRow)
Dim CheckBoxPractical as CheckBox = gvRow.FindControl("CheckBoxPractical")
If CheckBoxTheory.Checked = True Then
CheckBoxPractical.Checked = True
Else
CheckBoxPractical.Checked = False
End If
End Sub
This would get the sender as the checkbox, get the parent container (or NamingContainer), which would be a GridviewRow and then find the CheckBoxPractical control and then check if against the other checkbox value.
This is a long winded way of doing it but is the simplest at explaining the method.

Use LINQ with GridView

I am new to web dev and using controls so please forgive me.
I have a GridView with check boxes in it (please see markup below)
When a user goes through and checks any boxes and hits my submit button
I want to run LINQ query to get all the rows with the checkbox1.checked = True
Something like:
Dim sList = (From row in Gridview1
Where row.Cells("IsStarFleet") = True
row.Cells("ID)).ToList
Markup:
<asp:GridView ID="GridView1" runat="server" Width="516px" AutoGenerateColumns="False" AllowPaging="True">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:TemplateField HeaderText="IsStarFleet">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack ="False" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You need to use FindControl for controls in a TemplateField and Cells(index) for BoundFields:
Dim checkedIDs = From row In GridView1.Rows.Cast(Of GridViewRow)()
Where DirectCast(row.FindControl("CheckBox1"), CheckBox).Checked
Select row.Cells(0).Text
Dim checkedIdList = checkedIDs.ToList()

Finding out which button was clicked in a SelectedIndexChanged event handler of a GridView

We have a GridView that contains 2 "Select" buttons for each row that is displayed in the GridView.
We would like to know if there is a way to find out which of the 2 buttons was clicked on by using the SelectedIndexChanged handler.
This coding shows the buttons we have:
<asp:UpdatePanel
ID="UpdatePanelParentsSummary"
runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<p>Parent Search:
<asp:TextBox
ID="TextBoxSearch"
runat="server"
Width="207px"
Text="ALL"> </asp:TextBox>
<asp:Button
ID="ButtonSearch"
runat="server"
Text="Search" />
<asp:Button
ID="ButtonSearchAll"
runat="server"
Text="Show ALL Parents" />
<br />
</p>
<asp:GridView
ID="GridViewParentsSummary"
runat="server"
AllowPaging="True"
AllowSorting="True"
AutoGenerateColumns="False"
DataKeyNames="ID"
>
<Columns>
<asp:BoundField
DataField="ID"
HeaderText="ID"
SortExpression="ID" InsertVisible="False" ReadOnly="True" Visible="False" />
<asp:BoundField
DataField="FatherName"
HeaderText="FatherName"
SortExpression="FatherName" />
<asp:BoundField DataField="MotherName" HeaderText="MotherName"
SortExpression="MotherName" />
<asp:ButtonField
ButtonType="Button"
CommandName="Select"
Text="Select Details" />
<asp:ButtonField
ButtonType="Button"
CommandName="Select"
Text="New Person To Release Child" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
This is the code in the SelectedIndexChanged handler:
Protected Sub GridViewParentsSummary_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridViewParentsSummary.SelectedIndexChanged
IntParentsID = GridViewParentsSummary.DataKeys(GridViewParentsSummary.SelectedIndex).Value
Response.Redirect("AuthorizationForChildReleaseDetails.aspx")
End Sub
Ah, there is a simple solution to this problem. Your sender is the button clicked. Just try something like:
ButtonField buttonClicked = sender as ButtonField;
if (buttonClicked != null) {
String commandName = buttonClicked.CommandName;
if (commandName.equals("Command1") {
... do something awesome ...
} else if (commandName.equals("Command2")) {
... do something less awesome ...
}
}
I don't think you can differentiate between the source at the GridView event level because it is an event raised by the GridView at that point which is masking the lower level event. You can, however, implement a row level handler to identify which button was used to raise the event and set it up somewhere for use in the gridview event.
protected void GridView_RowCommand(object sender, CommandEventArgs e)
{
e.CommandArgument ....contains the argument name
....
}

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 ?

Query regarding binding the label in gridview ItemTemplate to String

I have a nested gridview lets call parent gridview as gridview1 and child gridview as gridview2.
For each parent gridview's (gridview1) row i'm adding child gridview (gridview2) depending upon the invoice number that is present on that particular row in the gridview1. Here is a screen shot of that output here.
Inside the child gridview (i.e., gridview2) i have a download linkbutton which i add through item template and software title which i databind to gridview2 after filtering the output that i get through List<>. But as you can see the download linkbutton is being rendered first and then software titles next. But i want the software titles to be rendered first and download link button as last column in child gridview (i.e., gridview2).
Here is the code in .aspx page for nested gridviews. I got a suggestion from a fellow member of this forum that I can add label before the download link button and associate it with data source. I just could n't understand it. How can one do that ?
<asp:GridView ID="UserTransactionGridView" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" OnRowDataBound="UserTransactionGridView_RowDataBound"
HorizontalAlign="Center" AllowPaging="true">
<Columns>
<asp:BoundField DataField="Date Of Transaction" HeaderText="Date Of Transaction"
SortExpression="Date Of Transaction" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="Invoice Number" HeaderText="Invoice Number" SortExpression="Invoice Number"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="totalAmount" HeaderText="Total Amount" ReadOnly="True"
SortExpression="totalAmount" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField>
<HeaderTemplate>
<asp:Label Text="Software Title" ID="softwareLbl" runat="server"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" GridLines="None"
ShowHeader="false">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:LinkButton ID="DownloadLbtn" Text="Download" runat="server" OnClick="DownloadLbtn_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:componentConnString %>"
SelectCommand="SelectUserPreviousHistory" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="xyz" Name="userName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
By the way here is the code where i'm binding child gridview with datasource (which is arraylist that i filter based on the invoice number present on the parent gridview (i.e., gridview1)).
protected void UserTransactionGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gridView2 = (GridView)e.Row.FindControl("gridView2");
System.Data.DataRowView dr = (System.Data.DataRowView)e.Row.DataItem;
gridView2.AutoGenerateColumns = true;
String x = dr[1].ToString();
softwareTitlesList = SoftwareListRetrieve();
ArrayList titles = new ArrayList();
foreach (SoftwareTitles softwareTitle in softwareTitlesList)
{
if (softwareTitle.InvoiceNumber.Contains(x))
titles.Add(softwareTitle.SoftwareTitle);
}
gridView2.DataSource = titles;
gridView2.DataBind();
softwareTitlesList.Clear();
}
}
BTW I'm using Visual studio 2008, asp.net/c# and no LINQ in my web application project.
Please help me.
Thank you in anticipation
PS: If some one doesn't like this question u may delete it after getting answered rather than down voting or flagging it.
1: Add AutoGenerateColumns="false" to your gv2
2: <%#Container.DataItem %> just before linkbutton
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" GridLines="None" ShowHeader="false" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<%#Container.DataItem %>
<asp:LinkButton ID="DownloadLbtn" Text="Download" runat="server" OnClick="DownloadLbtn_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can add a separate TemplateField instead of adding in same before the existing one but the you get the idea why it is showing next to linkbutton.

Resources