GridView RowCommand Event in Asp.Net

Description:-

In this article we will see about Gridview_RowCommand Event in dot net. Here I have created sample demo Project to Understand How to Work on Gridview_RowCommand Event. In this Demo Example I have bind Gridview from Database and Perform Action on that Gridview like Edit and Delete so user can Edit that item and Delete that Item. To Create Edit and Delete Inside Gridview you have to Create Columns in Gridview and from that Create Template Fields and Inside that Create Itemtemplate and Now Add Two Buttons for Edit and Delete.

Note: Here in Itemtemplate you can Bind Data Dynamically from Database like how I Done below. And For Increment Row Index I have used Container for Gridview row Index Generate.
Using the Command argument you can Get the Gridview selected Row Index Id and from that what action you have to Perform you can. For that you have to select RowCommandEventArgs to get ID for selected row.

Now Generate Gridview RowCommand from property and get ID from GridviewCommandEventArgs when you Select Gridview Row that it will select row Index from that Gridview for that you have to Add Command Argument and CommanName In Button Control. So when you Select Edit Button than it will fire Command Argument and Select what you have Bind in Command Argument. After what Action you have to Perform that you can Perform from ID. Here you can see Gridview RowCommand event Example What I have Dome.

Create Table and Name it "Item_Master".

CREATE TABLE [dbo].[Item_Master](
 [Item_ID] [int] IDENTITY(1,1) NOT NULL,
 [Item_Name] [varchar](20) NOT NULL,
 [Item_Rate] [real] NOT NULL,
 CONSTRAINT [PK_Item_Master] PRIMARY KEY CLUSTERED 
(
 [Item_ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Create Store Procedure for Edit Item_Master Data:

CREATE Procedure [dbo].[SP_EditItemDetails]
@ID int
as
begin
 select * from ItemDetails_Master where ID=@ID;
end
GO

Create Store Procedure for Delete Item_Master Data:

Create procedure [dbo].[SP_DeleteItemDetailsItem]
@ID int
as
begin
 delete from ItemDetails_Master where ID=@ID;
end

HTML Code:-

<div  style="margin:10px;">
  <asp:GridView ID="GridViewItem" runat="server" BackColor="LightGoldenrodYellow" AutoGenerateColumns="False"
  BorderColor="Tan" BorderWidth="1px" CellPadding="2" GridLines="None" Height="10px"
  Width="507px" ForeColor="Black" HorizontalAlign="Left" OnRowCommand="GridViewItem_RowCommand"
  OnRowDataBound="GridViewItem_RowDataBound" OnRowDeleting="GridViewItem_RowDeleting"
  OnRowEditing="GridViewItem_RowEditing" ShowFooter="true" PageSize="5">
  <AlternatingRowStyle BackColor="PaleGoldenrod" />
  <Columns>
    <asp:TemplateField HeaderText="Action" HeaderStyle-BorderStyle="Groove" ItemStyle-BorderStyle="Groove">
      <ItemTemplate>
        <asp:Button ID="btnedit" runat="server" CommandName="Edit" CommandArgument='<%#Eval("ID") %>' Text="Edit" />
        <asp:Button ID="btndelete" runat="server" Text="Delete" CommandArgument='<%#Eval("ID") %>' CommandName="Delete" />
      </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="ID">
      <ItemTemplate>
        <%#Container.DataItemIndex+1 %>
      </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Item Name">
      <ItemTemplate>
        <asp:Label ID="lbliname" runat="server" Text='<%#Eval("Item_Name") %>'></asp:Label>
      </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Item Rate">
      <ItemTemplate>
        <asp:Label ID="lblirate" runat="server" Text='<%#Eval("Item_Rate") %>'></asp:Label>
      </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Item Quantity">
      <ItemTemplate>
        <asp:Label ID="lbliqty" runat="server" Text='<%#Eval("Item_Quantity") %>'></asp:Label>
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
  <FooterStyle BackColor="Tan" />
  <HeaderStyle BackColor="Tan" Font-Bold="True" />
  <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
  <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
  <SortedAscendingCellStyle BackColor="#FAFAE7" />
  <SortedAscendingHeaderStyle BackColor="#DAC09E" />
  <SortedDescendingCellStyle BackColor="#E1DB9C" />
  <SortedDescendingHeaderStyle BackColor="#C2A47B" />
  </asp:GridView>
</div>

Code Behind:-

protected void GridViewItem_RowCommand(object sender, GridViewCommandEventArgs e)
{
  Int32 ID = Convert.ToInt32(e.CommandArgument.ToString());
  if (e.CommandName == "Edit")
  {
    using (con = new SqlConnection(CS))
    {
      cmd = new SqlCommand();
      cmd.CommandText = "SP_EditItemDetails";
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Connection = con;
      cmd.Parameters.AddWithValue("@ID", ID);
      con.Open();
      da = new SqlDataAdapter(cmd);
      dt = new DataTable();
      da.Fill(dt);
      if (dt.Rows.Count > 0)
      {
        itemdropdown.SelectedItem.Text = dt.Rows[0]["Item_Name"].ToString();
        txtitemrate.Text = dt.Rows[0]["Item_Rate"].ToString();
        txtitemquantity.Text = dt.Rows[0]["Item_Quantity"].ToString();
        txtitemtotalamount.Text = dt.Rows[0]["Item_Total"].ToString();
      }
    }
  }
  else if (e.CommandName == "Delete")
  {
    using (con = new SqlConnection(CS))
    {
      cmd = new SqlCommand();
      cmd.CommandText = "SP_DeleteItemDetailsItem";
      cmd.Parameters.AddWithValue("@ID", ID);
      cmd.Connection = con;
      cmd.CommandType = CommandType.StoredProcedure;
      con.Open();
      Int32 DeleteID = cmd.ExecuteNonQuery();
      if (DeleteID > 0)
      {
        lblmsg.Text = "Deleted !";
        lblmsg.ForeColor = System.Drawing.Color.Green;
        BindItemDetailsGrid();
      }
      else
      {
        lblmsg.Text = "Error : ID Not Found !";
      }
    }
  }
}

Now you are done for Gridview_RowCommand event for Perform any action from Gridview RowCommand event.

Related Posts

Previous
Next Post »

Thanks for comments.....