In gridview how to use rowcommand event for a button
Asked Answered
C

2

5

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 gridview in that GV i am supposed be use row command event for a button it should show the all the rsults for the students with the edit button as the last column for all the students i used item template for that. but in row command event i dont know the function to write if user clicking edit it should goto the edit page using the userid the id should be noon editable mode and other fields can editable.

details.aspx

   <asp:GridView ID="GridView3" runat="server" CellPadding="3" ForeColor="#333333" GridLines="None" AutoGenerateColumns="false"  OnRowCommand="GridView3_RowCommand" OnSelectedIndexChanged="GridView3_SelectedIndexChanged">
     <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
         <Columns>
             <asp:BoundField DataField="UserName" HeaderText="UserName" ReadOnly="True"/>
             <asp:BoundField DataField="Password" HeaderText="Password" />
             <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
             <asp:BoundField DataField="LastName" HeaderText="LastName" />
             <asp:BoundField DataField="EMail" HeaderText="Emaid-ID" />
             <asp:BoundField DataField="PhoneNo" HeaderText="Phone Number" />
             <asp:BoundField DataField="Location" HeaderText="Location" />

              <asp:TemplateField ShowHeader="False">
                <ItemTemplate>
                   <asp:Button ID="btnedit" runat="server" Text="Edit" CommandName="Edit" CommandArgument="UserName"/>
                </ItemTemplate>          
             </asp:TemplateField> 
         </Columns>
     <EditRowStyle BackColor="#999999" />
     <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
     <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
     <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
     <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
     <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
     <SortedAscendingCellStyle BackColor="#E9E7E2" />
     <SortedAscendingHeaderStyle BackColor="#506C8C" />
     <SortedDescendingCellStyle BackColor="#FFFDF8" />
     <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
 </asp:GridView>
    </div>
</form>

details.aspx.cs

 protected void Page_Load(object sender, EventArgs e)
 {
    string connection2 = System.Web.Configuration.WebConfigurationManager.ConnectionStrings        ["connection1"].ConnectionString;
    SqlConnection con = new SqlConnection(connection2);
    con.Open();
    SqlCommand cmd = new SqlCommand("select * from User_Information", con);
    SqlDataReader rdr = cmd.ExecuteReader();
    GridView3.DataSource = rdr;
    GridView3.DataBind();
    con.Close();
}
protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
{

}


protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
{

}

}

Chanda answered 16/7, 2014 at 6:28 Comment(1)
uh oh.. and dont forget to put the DataBind code at Page_Load inside if(!IspostBack)Texture
M
7

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;
    }
}
Metralgia answered 16/7, 2014 at 6:47 Comment(2)
I've found using "Edit" as the command name will always do the default edit. Need to use "myedit" or some other command string.Sheronsherourd
You can also use the following to get your Row, freeing up the CommandArgument for other uses GridViewRow gvr = (GridViewRow)((Button)e.CommandSource).NamingContainer as GridViewRow;Leannleanna
T
7

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.

Texture answered 16/7, 2014 at 10:58 Comment(1)
Hi Naveen and Ali Shahrokhi thanks for ur answers i tried both method and implemented thanks a lot... its working fine nowChanda

© 2022 - 2024 — McMap. All rights reserved.