Get Gridview Row Index
You can add OnRowCreteEvent
ASPX:
<asp:gridview id="gvESAPending" onrowcreated="gvESAPending_RowCreated" ...
CS :
protected void gvESAPending_RowCreated(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton addButton = (LinkButton)e.Row.Cells[0].Controls[0];
addButton.CommandArgument = e.Row.RowIndex.ToString();
}
}
Shantanu Sen
Updated on June 13, 2022Comments
-
Shantanu Sen almost 2 years
I am using the below code to get the row index
protected void gvESAPending_RowCommand(object sender, GridViewCommandEventArgs e) { try { lblMsg.Text = ""; int index = Convert.ToInt32(e.CommandArgument); GridViewRow row = gvESAPending.Rows[index]; // Here incorrect format error is coming } }
But the index value is coming as 0. What is wrong here?
Aspx Code
'> '>
-
Shantanu Sen over 11 yearsI got this error {System.InvalidCastException: Unable to cast object of type 'System.Web.UI.WebControls.GridView' to type 'System.Web.UI.WebControls.Button'.
-
GeorgesD over 11 yearsWhat is the error ? Can you give us the aspx code or follow the recommendation of @huMpty duMpty
-
Shantanu Sen over 11 yearsint index = Convert.ToInt32( e.CommandArgument); This is returning 0 so it should work. But its giving error
-
Shantanu Sen over 11 years<asp:ButtonField ButtonType="Button" CommandName="App" Text="Approve"> <ControlStyle BackColor="White" BorderStyle="None" Font-Underline="True" ForeColor="Blue" /> </asp:ButtonField> <asp:ButtonField ButtonType="Button" CommandName="Dec" Text="Decline"> <ControlStyle BackColor="White" BorderStyle="None" Font-Underline="True" ForeColor="Blue" /> </asp:ButtonField>
-
Shantanu Sen over 11 yearsHow will on rowcreate help .. I am not creating any row
-
GeorgesD over 11 yearsOk that why the index value is coming as 0. Can you explain what you wanna do ??
-
Shantanu Sen over 11 yearsAlready the gridview is bound with data .. I am clicking a buttonfield and thus need to get the row number
-
GeorgesD over 11 yearsgridview is bound with data so rows are created !
-
Shantanu Sen over 11 yearsall the examples are showing can be achieved by gvESAPending_RowCommand, why my code is not working .. am i missing something4
-
Shantanu Sen over 11 yearsIndex was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
-
Shantanu Sen over 11 yearsIndex was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
-
Pseudonym over 11 yearstry this
Int32.Parse(e.CommandArgument.ToString())
something may be screwy with the convert function, this should boil it down and give you something more useful to work with. If you really want to get fancy setstring var = e.CommandArgument.ToString()
put a break point right after it and check it out in the locals window to make sure your getting a value