In gridview how to use rowcommand event for a button

前端 未结 2 1569
深忆病人
深忆病人 2020-12-20 22:35

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

2条回答
  •  既然无缘
    2020-12-20 23:05

    Two methods To do this

    Method 1

    Please change these things in markup

    1. Change CommandName="EditUserName"
    2. Omit the CommandArgument. We don't need this

    Code-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

    1. CommandArgument="<%# Container.DataItemIndex %>"
    2. CommandArgument="<%# Container.DisplayIndex %>"
    3. 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.

提交回复
热议问题