so i have a gridview with an imagebutton, thing is that it never triggers. I dont know why. here is the code.
<asp:GridView ID="GridView1" runat="server" Width="233px"
OnCommand="GridView1_RowCommand" onrowcommand="GridView1_RowCommand"
DataKeyNames="Nombre">
<Columns>
<asp:TemplateField HeaderText="" ItemStyle-Width="12%" ItemStyle-
HorizontalAlign="Center" >
<ItemTemplate>
<asp:ImageButton ID="lnkEditar" runat="server" CommandName="Edit"
ImageUrl="Imagenes/edit.png" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and the code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int index = Convert.ToInt32(e.CommandArgument);
Label1.Text = GridView1.Rows[index].Cells[2].ToString();
}
}
I debugged it and it never triggers the RowCommand event. Any help is thanked!
Try to change as follow OnRowCommand
OnRowCommand="GridView1_RowCommand"
Related
I'm trying to populate multiple text boxes with data from a gridview when I click the link button (which is in fact the name of one of the fields in each row) but it isn't going through. I'm new to this - literally my first time. Any help would be most appreciated.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
AccountNumber.Text = selectedRow.Cells[1].Text;
Name.Text = selectedRow.Cells[1].Text;
Address1.Text = selectedRow.Cells[1].Text;
Address2.Text = selectedRow.Cells[2].Text;
Address3.Text = selectedRow.Cells[3].Text;
PhoneNumber.Text = selectedRow.Cells[4].Text;
FaxNumber.Text= selectedRow.Cells[5].Text;
CurrencyID.Text = selectedRow.Cells[6].Text;
}
}
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="Agent_Account_No"
DataSourceID="SqlDataSource1"
AlternatingRowStyle-BackColor ="Lavender"
HeaderStyle-BackColor="#9966FF"
AllowSorting="True" HeaderStyle-BorderColor="Black"
HorizontalAlign="Center"
RowStyle-BorderColor="Black"
EmptyDataText="There are no data records to display."
onrowcommand ="GridView1_RowCommand">
<AlternatingRowStyle BackColor="#CCFFCC" />
<Columns>
<asp:BoundField datafield="Agent_Account_No" HeaderText="Account No"
ItemStyle-HorizontalAlign="Center"
ItemStyle-VerticalAlign="Middle"
ItemStyle-Width="50"
SortExpression="Agent_Account_No"
ReadOnly="true">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"
Width="50px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Name" SortExpression="Agent_Name">
<ItemTemplate>
<asp:LinkButton ID="AgentName" runat="server"
Text='<%# Eval("Agent_Name") %>'
CommandName="Select"
CommandArgument='<%#Bind("Agent_Name") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
I got it to work this way - using help from this site:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
AccountNumber.Text = GridView1.DataKeys[row.RowIndex]["Agent_Account_No"].ToString();
......
}
I don't know if this declaration is right, but it works. However now that it works I see a problem that I didn't see before - see my profile and thanks a lot!
I would highly recommend using TemplateFields for all of your columns, like this:
Markup:
<Columns>
<asp:TemplateField HeaderText="Account No" SortExpression="Agent_Account_No">
<ItemTemplate>
<asp:Label ID="LabelAccountNumber" runat="server"
Text='<%# Eval("Agent_Account_No") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
...
<asp:TemplateField HeaderText="Name" SortExpression="Agent_Name">
<ItemTemplate>
<asp:LinkButton ID="AgentName" runat="server"
Text='<%# Eval("Agent_Name") %>'
CommandName="Select"
CommandArgument='<%#Bind("Agent_Name") %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Now in the RowCommand method, you can use the FindControl() method of the grid view row to get to the text you are interested in, like this:
Code-behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
// Find the account number label to get the text value for the text box
Label theAccountNumberLabel = selectedRow.FindControl("LabelAccountNumber") as Label;
// Make sure we found the label before we try to use it
if(theAccountNumberLabel != null)
{
AccountNumber.Text = theAccountNumberLabel.Text;
}
// Follow the same pattern for the other labels to get other text values
}
}
I have a LinkButton inside a GridView that passes a CommandArgument and tries to fire RowCommand
GridView declaration:
<asp:GridView PageIndex="0" OnRowCommand="GridView1_RowCommand" PageSize="10" AllowPaging="true" OnPageIndexChanging="GridView1_PageIndexChanging"
ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None"
BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" Width="700px"
AutoGenerateColumns="False" OnPageIndexChanged="GridView1_PageIndexChanged">
LinkButton inside the GridView:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" OnClientClick="return confirm('Are you sure you want to delete this checklist?');" runat="server" CausesValidation="false" CommandName="DeleteChecklist" CommandArgument='<%# Eval("refID") %>' Text="Delete"></asp:LinkButton>
</ItemTemplate>
<ItemStyle ForeColor="Black" />
<ControlStyle BorderStyle="None" ForeColor="Black" />
</asp:TemplateField>
Code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteChecklist")
{
string refID = e.CommandArgument.ToString();
DAL.DeleteChecklist(refID);
}
}
I placed a breakpoint at RowCommand but it doesn't get fired at all, any idea why?
I assume that you're databinding the GridView on postbacks. So always embed it in a if(!IsPostBack) check:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
GridView1.DataSource = getSource();
GridView1.DataBind();
}
}
Otherwise events won't be triggered and edited values will be overridden.
Another possible reason: Have you disabled ViewState?
EDIT2: Ok it got better. You can make it work with AllowCustomPaging="true" but the property VirtualItemCount must have to be greater than the PageSize value of your grid view. Look at this:
<asp:GridView runat="server" ID="gvPresupuestos" AutoGenerateColumns="False"
OnRowCommand="gvPresupuestos_RowCommand"
OnPageIndexChanging="gvPresupuestos_PageIndexChanging"
OnPreRender="gvPresupuestos_PreRender" ItemType="Core.NominaEntities.TipoPresupuesto"
AllowPaging="true" PageSize="1" AllowCustomPaging="true"
UseAccessibleHeader="true" GridLines="None" CssClass="table table-hover"
ShowHeaderWhenEmpty="True">
<Columns>
<asp:BoundField HeaderText="Nombre del presupuesto" DataField="Nombre" />
<asp:TemplateField HeaderText="Opciones">
<ItemTemplate>
<a href='<%# "Detalle?p=" + Item.IdTipoPresupuesto.ToString() %>'
target="_self"><%# Item.Editable ? "Editar" : "Ver" %></a>
<asp:LinkButton runat="server"
CommandArgument='<%# Item.IdTipoPresupuesto.ToString() %>'
CommandName="Deshabilitar"
Text="Deshabilitar" Visible='<%# !Item.Editable ? true : false %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
FillView() method:
private void FillView(int desiredPage)
{
var cliente = ClientFactory.CreateAuthServiceClient();
using (cliente as IDisposable)
{
// this list only has 1 item.
List<TipoPresupuesto> resultado = cliente.ObtenerTiposDePresupuesto();
gvPresupuestos.DataSource = resultado;
// For testing pursposes, force the virtual item count to 1000.
gvPresupuestos.VirtualItemCount = 1000;
gvPresupuestos.DataBind();
}
}
So, the LinkButton does not fire the gvPresupuestos_RowCommand event unless the virtual item count is greater than the VirtualItemCount property.
I hope this helps.
EDIT1: I found it. You can make it work by changing the value of "AllowCustomPaging" to false. I don't know why, but hope this can help.
ORIGINAL 'ANSWER':
I have the same problem. You can see the my code here:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<div class="jumbotron jumbotron-small">
<h2>Presupuestos</h2>
</div>
<asp:GridView runat="server" ID="gvPresupuestos"
AutoGenerateColumns="False" AllowPaging="true" AllowCustomPaging="true" PageSize="20"
OnRowCommand="gvPresupuestos_RowCommand"
OnPageIndexChanging="gvPresupuestos_PageIndexChanging"
DataKeyNames="IdTipoPresupuesto" OnPreRender="gvPresupuestos_PreRender"
ItemType="Core.NominaEntities.TipoPresupuesto" ShowHeaderWhenEmpty="True"
UseAccessibleHeader="true" GridLines="None" CssClass="table table-hover">
<Columns>
<asp:BoundField HeaderText="Nombre del presupuesto" DataField="Nombre"/>
<asp:TemplateField HeaderText="Opciones">
<ItemTemplate>
<asp:LinkButton runat="server" Text="Deshabilitar"
Font-Underline="true" CommandName="Deshabilitar"
Visible='<%# Item.Editable ? true : false %>'
CommandArgument='<%# Item.IdTipoPresupuesto %>' />
<a href='<%# "Detalle?p=" + Item.IdTipoPresupuesto.ToString() %>'
target="_self"><%# Item.Editable ? "Editar" : "Ver" %></a>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Link" CommandName="Deshabilitar"
Text="Deshabilitar (this fires event)" />
</Columns>
</asp:GridView>
<table class="large-table">
<tr>
<td class="text-right">
<a runat="server" class="btn btn-primary" href="Detalle">Nuevo presupuesto</a>
</td>
</tr>
</table>
</asp:Content>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
InitializeControls();
SetPermissions();
FillView(1);
}
}
protected void gvPresupuestos_PreRender(object sender, EventArgs e)
{
// Habilita bootstrap
gvPresupuestos.HeaderRow.TableSection = TableRowSection.TableHeader;
}
protected void gvPresupuestos_RowCommand(object sender, GridViewCommandEventArgs e)
{
// This is never fired by the LinkButton in the ItemTemplate
// But the ButtonField actually fires it.
if (e.CommandName.Equals("Deshabilitar"))
{
// This is how I've been doing it in the whole project but thanks to this
// shit I can't use the CommandArgument of the LinkButton in the ItemTemplate
// Guid idPresupuesto = new Guid(e.CommandArgument.ToString());
// I don't know what I'm supposed to do now.
// ¿Why this only happens in this page?, ¿WTF?
Guid idPresupuesto = gvPresupuestos.GetTheIdFromDataKeysWithFuckingMagic();
var cliente = ClientFactory.CreateServiceClient();
using (cliente as IDisposable)
{
cliente.DeshabilitarPresupuesto(idPresupuesto);
}
}
FillView(1);
}
protected void gvPresupuestos_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvPresupuestos.PageIndex = e.NewPageIndex;
FillView(e.NewPageIndex + 1);
}
#region helper methods
private void InitializeControls()
{
// Not required yet
}
private void FillView(int desiredPage)
{
var cliente = ClientFactory.CreateAuthServiceClient();
using (cliente as IDisposable)
{
var resultado = cliente.ObtenerTiposDePresupuesto();
gvPresupuestos.DataSource = resultado;
gvPresupuestos.DataBind();
}
}
private void SetPermissions()
{
// not required yet
}
#endregion
I've tried enabling and disabling viewstate in the gridview but didn't get different results.
Here is what happens with breakpoints:
You type the url and load the page for the first time.
Then you access the code in the block if(!IsPostBack).
Now you can click both the LinkButton in the ItemTemplate and the ButtonField(Look screenshot)
If you click the LinkButton in the ItemTemplate, it doesn't fire gvPresupuestos_RowCommand. It does a postback, of course. But gvPresupuestos_RowCommand simply doesn't get fired. My code doens't handle that weird postback and the page does the things it would do with a regular postback. After it, you end up with an empty gridview because in the flow of this postback, FillView() is never called.(Look screenshot)
If you click the ButtonField, the event gvPresupuestos_RowCommand is fired, and everything is normal. But I require the IdPresupuesto of the clicked row and I don't know how to get it now.
This is weird. I've implemented this model in all the info pages of the system (there are like 15 modules like this) and never had problems until now.
I had the same problem for a LinkButton in a ListView.
Turns out I should have been using OnItemCommand in the ListView, not OnRowCommand.
Changing this fixed the issue.
Also, you must have a CommandName set on the LinkButton (but no OnCommand).
Using CSharp, I'm not getting into the (GridView1_RowDeleting) function on the button click.. I don't know whats the problem is but wasted alot of time on it.
Default.aspx
asp:GridView ID="GridView1" runat="server" OnRowDeleting="GridView1_RowDeleting"
AllowPaging="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="img1" runat="server" CommandName="GridView1_RowDeleting" ImageUrl="~/Images/cross.png" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Default.aspx.cs
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
Use OnItemCommand:
protected void Test(object sender,DataGridEventArgs e)
{
if(e.CommandName == "GridView1_RowDeleting")
{
// do something
}
}
<asp:GridView ID="GridView1" runat="server" OnItemCommand="Test" AllowPaging="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="img1"
runat="server"
CommandName="GridView1_RowDeleting"
ImageUrl="~/Images/cross.png" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You have to use the OnCommand property of ImageButton:
Please update your code with following.
Write OnCommand="GridView1_RowDeleting"
I hope it would work.
protected void GridView1_RowDeleting(object sender, CommandEventArgs e)
{
// Do something
}
I have a GridView bound to an object datasource and a hover menu extender over that. On the panel that pops up I have two buttons - one for delete and one for edit. The problem I'm having is identifying which row triggered the hover menu so I know what to delete. I've searched all over the site and found similar issues but I wasn't able to apply them properly. I followed this video, and was able to get a hidden field to maintain the ID but only of the last row that was created, so my delete button always removed the last entry. I hope that was somewhat clear..
Here is my gridview code:
<asp:GridView runat="server" AutoGenerateColumns="False"
DataSourceID="source_Layout_view" ID="GridView1"
onrowdatabound="GridView1_RowDataBound"
onrowcreated="GridView1_RowCreated">
<Columns>
<asp:BoundField DataField="type" HeaderText="type" SortExpression="type" />
<asp:BoundField DataField="code" HeaderText="code" SortExpression="code" />
<asp:BoundField DataField="description" HeaderText="description"
SortExpression="description" />
<asp:BoundField DataField="position" HeaderText="position"
SortExpression="position" />
<asp:BoundField DataField="sequence" HeaderText="sequence"
SortExpression="sequence" />
<asp:TemplateField>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="img_edit" runat="server" ImageUrl='~/ui/images/wrench.png' Width="25px" Height="25px" />
<asp:HoverMenuExtender ID="gridview_options_extender" runat="server" PopupControlID="gridview_options_popup" TargetControlID="img_edit"
OffsetX="10" OffsetY="10" PopupPosition="Right" PopDelay="50" HoverDelay="50" >
</asp:HoverMenuExtender>
<asp:Panel ID="gridview_options_popup" runat="server">
<asp:Button ID="btn_popup_delete" runat="server" Text="Delete Unit" OnClick="deleteRow"/>
<br />
<asp:Button ID="btn_popup_edit" runat="server" Text="Edit Unit" />
<asp:HiddenField ID="tellmeRow" runat="server" Value='Eval("ID")'/>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and here is my code behind
protected void deleteRow(object sender, EventArgs e)
{
Button b = sender as Button;
Panel x = b.Parent as Panel;
HiddenField whatiwant = (HiddenField)x.FindControl("tellmeRow");
int idForDeletion = Int32.Parse(whatiwant.Value);
using (var context = new cocoEntities())
{
context.CoCo_Current.DeleteObject(context.CoCo_Current.Single(o => o.ID == idForDeletion));
context.SaveChanges();
}
Response.Redirect("default.aspx");
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HoverMenuExtender menu = (HoverMenuExtender)e.Row.FindControl("gridview_options_extender");
e.Row.ID = e.Row.RowIndex.ToString();
menu.TargetControlID = e.Row.ID;
}
}
}
Don't use button click handler to do some action on a GridView. Assign instead apropriate CommandName property value for button and handle GridView's RowCommand event. GridView.RowCommand Event
I have this gridview:
<div class="content">
<asp:GridView ID="DocumentGrid" runat="server" AutoGenerateColumns="False" OnRowCommand="DocumentGrid_RowCommand" >
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" ItemStyle-Width="120px"/>
<asp:ButtonField HeaderText="Download Link" Text="Download"/>
</Columns>
</asp:GridView>
</div>
As you can see, DocumentGrid_RowCommand is called when the "Download" button is pressed, How can I find out what the values are of the row that was clicked?
If more than one button fields are there in GridView, set CommandName attribute. That way we can determine which button is pressed in RowCommand event. So always set commandName attribute.
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" ItemStyle-Width="120px"/>
<asp:ButtonField HeaderText="Download Link" Text="Download" CommandName="cmd"/>
</Columns>
In RowCommand event handler, GridViewCommandEventArgs.CommandArgument property returns index of row on which button is pressed.
protected void DocumentGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "cmd")
{
int index = int.Parse(e.CommandArgument.ToString());
GridViewRow row = DocumentGrid.Rows[index];
if (row.RowType == DataControlRowType.DataRow)
{
Response.Write(row.Cells[0].Text);
}
}
}
If you set the markup like this,
<Columns>
<asp:TemplateField HeaderText="Download">
<ItemTemplate>
<asp:Button ID="btnDownload" CommandName="Download" CommandArgument='<%# Container.DataItemIndex %>'
runat="server" Text="Download" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
on the code-behind you can check the CommandArgument like this:
if (e.CommandName == "Download")
{
int index = Convert.ToInt32(e.CommandArgument);
}