I am using a gridview in aspx and i have two pages that registration and details.aspx once registration completed it should goto details page in details.aspx i have kept a g
First your button control CommandArgument
property must have a unique value in each row:
<asp:Button ID="btnedit" runat="server" Text="Edit" CommandName="Edit"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
Then on your code behind GridView3_RowCommand
event you will have something like the code below:
protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = 0;
GridViewRow row;
GridView grid = sender as GridView;
switch (e.CommandName)
{
case "Edit":
index = Convert.ToInt32(e.CommandArgument);
row = grid.Rows[index];
//use row to find the selected controls you need for edit, update, delete here
// e.g. HiddenField value = row.FindControl("hiddenVal") as HiddenField;
break;
}
}
Two methods To do this
Method 1
Please change these things in markup
CommandName="EditUserName"
CommandArgument
. We don't need thisCode-behind
protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditUserName")
{
//first find the button that got clicked
var clickedButton = e.CommandSource as Button;
//find the row of the button
var clickedRow = clickedButton.NamingContainer as GridViewRow;
//now as the UserName is in the BoundField, access it using the cell index.
var clickedUserName = clickedRow.Cells[0].Text;
}
}
Method 2
Give a CommandArgument
. You can give many different arguments like these
CommandArgument="<%# Container.DataItemIndex %>"
CommandArgument="<%# Container.DisplayIndex %>"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
(the one Ali gave)Now in code, do this
protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditUserName")
{
var clickedUserName = CustomersTable
.Rows[Convert.ToInt32(e.CommandArgument)]//find the row with the clicked index
.Cells[0]//find the index of the UserName cell
.Text;//grab the text
}
}
P.S:
1.The reason for changing the CommandName is that if the CommandName="Edit"
, it will fire the RowEditing
event which will give you this error
The GridView 'GridView3' fired event RowEditing which wasn't handled.
2.Place the Page_Load code inside if(!IsPostBack)
or else none the above methods work.