Reputation: 12843
I have an asp.net GridView:
<asp:TemplateField HeaderText="View Faktor" ShowHeader="False" Visible="True">
<ItemTemplate>
<asp:ImageButton ID="imgBtn1" CssClass="SelectRow" runat="server" CausesValidation="false"
CommandArgument='<%#(eval("mprID")) %>' CommandName="ViewFactors" ImageUrl="~/tadarokat/Images/factor.png"
Text="" />
</ItemTemplate>
</asp:TemplateField>
How Can I get rowIndex
on row command event?
I want to highlight (select
) target row when RowCommand
fires.
Upvotes: 37
Views: 126602
Reputation: 1
You can also put the grid row number into one of your grid controls .CommandArgument properties when loading the grid, then retrieve the value on gridview.RowCommand when selected:
Upvotes: 0
Reputation: 10755
this is answer for your question.
GridViewRow gvr = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
int RowIndex = gvr.RowIndex;
Upvotes: 78
Reputation: 51
If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:
int index = Convert.ToInt32(e.CommandArgument);
In a custom command, you can set the command argument to yourRow.RowIndex.ToString()
and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.
Upvotes: 5
Reputation: 71
I was able to use @rahularyansharma's answer above in my own project, with one minor modification. I needed to get the value of particular cells on the row on which the user clicks a LinkButton
. The second line can be modified to get the value of as many cells as you wish.
Here is my solution:
GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
string typecore = gvr.Cells[3].Text.ToString().Trim();
Upvotes: 2
Reputation: 11
protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Delete")
{
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RemoveAt = gvr.RowIndex;
DataTable dt = new DataTable();
dt = (DataTable)ViewState["Products"];
dt.Rows.RemoveAt(RemoveAt);
dt.AcceptChanges();
ViewState["Products"] = dt;
}
}
catch (Exception ex)
{
throw;
}
}
protected void gvProductsList_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
gvProductsList.DataSource = ViewState["Products"];
gvProductsList.DataBind();
}
catch (Exception ex)
{
}
}
Upvotes: 1
Reputation:
Or, you can use a control
class instead of their types:
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int RowIndex = row.RowIndex;
Upvotes: 7
Reputation: 960
ImageButton \ Button etc.
CommandArgument='<%# Container.DataItemIndex%>'
code-behind
protected void gvProductsList_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = e.CommandArgument;
}
Upvotes: 15