ASP.NET Gridview button onclick not firing - asp.net

Hi all I have a simpe ASP button inside a grid. But the onclick event doesn't seem to fire. Where did I go wrong?
Here's the first line of my aspx page.
<%# Page Title="Trainer Data" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeFile="TrainerData.aspx.vb" Inherits="TrainerData"%>
And the button inside my gridview..
<asp:GridView ID ="gvExecSummary" runat="server" CssClass="gridview" AllowSorting="false" AllowPaging="false" AutoGenerateColumns="false" Width="98%" >
<RowStyle Height="22px" />
<AlternatingRowStyle Height="22px" CssClass="bg" BackColor="LightGray"/>
<HeaderStyle Height="22px" BackColor="#4b6c9e" Font-Bold="true"/>
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="5%" HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate" OnClientClick="btnExecutiveGenerate_Click" />
</ItemTemplate>
</asp:TemplateField>
P.S. I tried even onclick but it doesn't work either.
EDIT: My code for server side.
Protected Sub btnExecutiveGenerate_Click(sender As Object, e As EventArgs)
Dim gvrow As GridViewRow = CType(CType(sender, Control).Parent.Parent, GridViewRow)
Dim lblSchoolId As System.Web.UI.WebControls.Label = gvrow.FindControl("lblSchoolMasterID")
Dim lblFacultyId As System.Web.UI.WebControls.Label = gvrow.FindControl("lblFacultyMasterID")
Dim btnExecutiveGenerate As System.Web.UI.WebControls.Button = gvrow.FindControl("btnExecutiveGenerate")
PDF_Creation_Executive(Val(lblSchoolId.Text), Val(lblFacultyId.Text))
End Sub

Use Command Argumnet,
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
add code page side
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

You need to handle the button click event of Gridview in RowCommand event
NOTE: Please see the CommandName & CommandArgument properties added to the button.
<asp:GridView ID ="gvExecSummary" runat="server" CssClass="gridview" AllowSorting="false" AllowPaging="false" AutoGenerateColumns="false" Width="98%" >
<RowStyle Height="22px" OnRowCommand="gvExecSummary_RowCommand" />
<AlternatingRowStyle Height="22px" CssClass="bg" BackColor="LightGray"/>
<HeaderStyle Height="22px" BackColor="#4b6c9e" Font-Bold="true"/>
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderStyle-Width="5%" HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate" CommandName="GenerateExecutive" CommandArgument="<%#((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
And and RowCommand event will be..
protected void gvExecSummary_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "GenerateExecutive")
{
// button click code goes here
}
}

change OnClientClick event to OnClick if btnExecutiveGenerate_Click is vb.net event handler
<asp:Button ID="btnExecutiveGenerate" runat="server" Text="Generate"
OnClick="btnExecutiveGenerate_Click"/>
OnClientClick event use to execute client-side script, if you have given OnClientClick event with OnClick event, then if OnClientClick return true only it will call OnClick event.
so make sure you are returning true or false from OnClientClick event if you using it.
note that if you are loading data in page laod, do as below
Sub Page_Load
If Not IsPostBack
LoadGridViewData()
End If
End Sub

This may help someone, but I was experiencing edit buttons not firing the event within rows (and not footer).
The cause was a gridview containing a label, which had the same ID as one elsewhere on the page.
Seemingly this did not cause problems for the footer row, which did not contain any such labels.
I hope this helps someone.

Related

Asp.net user control item command event not firing

I have a page which has user control in it.
The page data grid bound columns are populated from user control (user control has a data grid whose items are in the form of item templates).
This user control has a column which contains edit save cancel buttons.
The user control also has other columns which are check boxes,drop down lists inside (item templates).
I am using item command event and when Edit link is clicked it should get current row value of a column called "Description" and for testing purpose I am getting this value into a text box called 'Tdval'.
The Tdval textbox is empty and when I check break point it looks like item command event is not all firing( as break point is not hit).
I don't understand why.
The page is not posted back when I click Edit link.
Its just the user control link button. Please help me.
Excuse any mistakes and am new to this. Thanks in advance.
HTML:
<tr>
<asp:datagrid ID="dgDetails"
EnableViewState="true"
runat="server"
onItemCommand="dgDetails_ItemCommand"
allowpaging="false"
allowcustompaging="false"
autogeneratecolumns="false"
allowsorting="true"
backcolor="white"
Width="100%"
horizontalalign="center"
Font-bold="true"
Font-Names="Verdana"
Font-size="7pt"
BorderColor="Silver" >
<columns>
<asp:BoundColumn DataField="ID" Visible="true"></asp:BoundColumn>
<asp:TemplateColumn HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Left"
HeaderText="Description"
HeaderStyle-Width="320px" >
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server">
<%#DataBinder.Eval(Container.DataItem, "Description")%>
</asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderStyle-HorizontalAlign="Left"
ItemStyle-HorizontalAlign="Left"
HeaderText="Pr."
HeaderStyle-Width="20px" >
<ItemTemplate>
<asp:CheckBox ID="chkPrimary" runat="server" Enableviewstate="true">
</asp:CheckBox>
</ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server"
CommandName="Edit">Edit
</asp:LinkButton>
</columns>
</asp:datagrid>
</tr>
<tr>
<td>
<asp:TextBox ID="Tdval" runat="server"> </asp:TextBox>
</td>
Code Behind:
Public Sub dgDetails_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles dgDetails.ItemCommand
Select Case e.CommandName
Case "Edit"
Dim intRow As Integer
intRow = e.Item.ItemIndex
Dim dgRow As DataGridItem
dgRow=dgDetails.Items.Item(intRow)
Dim val As String
val=Ctype(dgRow.Cells(0).Text, String) (Description column)
Tdval.Text=val.Text
End Select
End Sub
I thing u can call bindGrid() method after check page.ispostback on page_load like this :
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
return;
}
BindGrid();
}

Grid Checkbox value not changed, how to get value on button click?

i am using asp.net for my web application when i click on checkbox inside gridview and after that i check its value on button click it does not show me the exact value
here is asp code
<asp:GridView ID="dgvMenu" runat="server" Width="100%" CssClass="grid" GridLines="None"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
View
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="View" runat="server" Checked="<%#Bind('View') %>" />
</ItemTemplate>
<ItemStyle Width="50px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="Menu" HeaderText="Menu Name">
<HeaderStyle HorizontalAlign="Left" CssClass="firstcol" />
<ItemStyle CssClass="firstcol" />
</asp:BoundField>
</Columns>
</asp:GridView>
and here is its vb version to get its value on button click version
For Each item As GridViewRow In dgvMenu.Rows
Dim MenuName As String = item.Cells.Item(1).Text
Dim chkView As CheckBox = DirectCast(item.FindControl("View"), CheckBox)
Next
i want to check its value whether its checked or unchecked so that i can process its value
I assume that your binding your GridView even on postbacks. You should only bind it if not PageIsPostback.
Put this into Page_Load:
Private Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' following function loads data and binds it to the GridView '
BindGrid()
End If
End Sub
If you DataBind the Grid on every postback, ViewState cannot be reloaded, hence all changed values are lost and events will not be triggered correctly.

How to access a button inside a listview? specifically using the button_click to carry out an action

I have this simplified code:
<asp:ListView ID="ListView1" runat="server" DataSourceID="sqldatasource1">
<ItemTemplate>
<asp:Button ID="ButtonTest" runat="server" BackColor="Silver" Text="Add to Cart" />
</ItemTemplate>
</asp:ListView>
I am trying to run some code behind the button but I don't know how. I can't access it within the listview. Not that this is important, but im trying to get information from the current listview(the product ID) and pass it to the next page.
Anybody know how to approach this, with the exact code? Thanks!
You want the ItemCommand event. You would give your button a command name, a command argument (if you want), then listen for the ItemCommand event on the ListView
<asp:ListView ID="ListView1" runat="server" OnItemCommand="DoTheCommand" DataSourceID="sqldatasource1">
<ItemTemplate>
<asp:Button CommandName="Foo" CommandArgument='<%#Eval("SomeDataBoundProperty")%>' ID="ButtonTest" runat="server" BackColor="Silver" Text="Add to Cart" />
</ItemTemplate>
</asp:ListView>
And in your code behind:
void DoTheCommand(object sender, ListViewCommandEventArgs e) {
string commandName = e.CommandName;
object commandArg = e.CommandArgument;
ListViewItem selectedItem = e.Item;
int dataItemIndex = selectedItem.DataItemIndex;
if (commandName == "Foo") {
//and so on
}
}
U can use ListView's ItemCommand Event in codebehind with commandName and command argument set in aspx.
<asp:ListView ID="ListView1" runat="server" DataSourceID="sqldatasource1">
<ItemTemplate>
<asp:Button ID="ButtonAdd" runat="server" BackColor="Silver" CommandName="cAdd" CommandArgument= '<%# Eval("ProductId") %>' Text="Add to Cart" />
Protected Sub ListView1_OnItemCommand(ByVal sender As Object, _
ByVal e As ListViewCommandEventArgs) Handles Listview1.ItemCommand
If String.Equals(e.CommandName, "cAdd") Then
Dim ProductId as integer = e.CommandArgument
'your code
End If
End Sub

Replace buttoncolumn "Delete" with a Image Button in Gridview

This is my Gridview code
<asp:DataGrid id="dg" runat="server" ondeletecommand="Delete_Item" >
<columns>
<asp:buttoncolumn buttontype="LinkButton" commandname="Delete" text="Remove" />
</columns>
<HeaderStyle BackColor="#95C736" ForeColor="White" Font-Bold="True" />
</asp:DataGrid>
I want to replace my buttoncolumn with an image, what must I do to my GridView?
I would use a template column for this:
<asp:DataGrid ID="DataGrid1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="/images/delete.png" CommandName="Delete" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Replace the Button Column with a TemplateColumn with allows you to put standard asp controls inside. Then you can handle the Datagrid_ItemCommand event normally.
<asp:DataGrid ID="dgTest" runat="server">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:ImageButton ID="ibtnDelete" runat="server" CommandName="cmdDelete"
ImageUrl="~/images/delete.png" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
The ItemCommand handler would be something like:
Protected Sub dgTest_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles dgTest.ItemCommand
If (e.CommandName = "cmdDelete") Then
Response.Write("the command argument was :" & e.CommandArgument)
End If
End Sub
The only other thing you would need to do is bind some data to the image button for a command argument. I usually do something like:
Protected Sub dgTest_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgTest.ItemDataBound
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim di As FAQTable = e.Item.DataItem
DirectCast(e.Item.FindControl("ibtn"), ImageButton).CommandArgument = di.FAQID
End If
End Sub
You could also use an asp:image control with an asp:Hyperlink control to get the same results.
One thing I just did that worked awesome is to put encoded html into the text. Text="<img src='images/btn-find.png' class='ttip' alt='View Details' />" This let me know only put in the img src, but also specify a class and an alt tag.
All you need to do is use single tick marks and encode your <> with gt and lt.

gridview button with databound drop down fails

I have a gridview with a button, and when the button is clicked, it fires a rowcommand procedure and adds a new row to the database. Everything works fine until I add a databound drop down list to the gridview.
With a databound dropdown list, the page loads fine, but when I click the button the error shows as "Internet Explorer cannot display the webpage". here is my code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand"
DataSourceID="SqlDataSource1">
<Columns>
<asp:ButtonField CommandName="insertNew"
Text="Button" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnAdd" runat="server" CommandName="insertNew"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
Text="Add" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField></asp:TemplateField>
</Columns>
</asp:GridView>
And here is my code behind that runs when the button is pressed;
Protected Sub GridView1_RowCommand(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "insertNew") Then
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
MsgBox(index)
End If
End Sub
I just had to put this into the system.web web.config file
<httpRuntime maxRequestLength="32768" />
The problem is in the MsgBox line. MsgBox(index) is not supported in web applications.
Please remove MsgBox(index), and the issue will be fixed, because that feature is only supported in Windows Applications.

Resources