Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Respond to Button Events in a GridView Control

Posted by Ravi Varma Thumati on November 12, 2009

When a button is clicked in a GridView control, the RowCommand event is raised. The GridView control has built-in functionality for operations such as edit, delete, and paging. You can also add buttons and use the RowCommand event to add custom functionality to the control.

You can add custom functionality to a GridView control in the following ways:

  • By adding a ButtonField field to the GridView control.
  • By adding a Button, LinkButton, or ImageButton controls to a template in the GridView control.

You can use the CommandName property of the event argument to identify the button’s function in the event handler method. If you are working with ButtonField or TemplateField objects, you can also use the CommandArgument property to identify the current row. When you are using a ButtonField object, the CommandArgument property is set automatically to the row index. When you are using a TemplateField object, the CommandArgument property is not automatically set by the control. In that case, if you have to determine the row index in the event handler, you can set the CommandArgument property of the button to the row index by using a data-binding expression.

To respond to button events in the GridView control

  1. Set the button’s CommandName property to a string that identifies its function, such as “Print” or “Copy”.
  2. If you are using the TemplateField object and have to access the row index in the event handler method set the button’s CommandArgument property to an expression that identifies the current row.

The following example shows how you can set the CommandArgument property of a button in a TemplateField column to the current row index. In the example, the column contains a Button control that displays a shopping cart.

Visual Basic

<asp:TemplateField>
  <ItemTemplate>
    <asp:Button runat="server"
      CommandName="AddToCart"
      CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
      Text="Add to Cart" />
  </ItemTemplate>
</asp:TemplateField>

C#

<asp:TemplateField>
  <ItemTemplate>
    <asp:Button runat="server"
      CommandName="AddToCart"
      CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
      Text="Add to Cart" />
  </ItemTemplate>
</asp:TemplateField>
  1. Create a method for the RowCommand event of the GridView control. In the method, do the following:
    1. Check the CommandName property of the event-argument object to see what string was passed.
    2. Retrieve the index of the row that contains the button by using the CommandArgument property, if required.
    3. Perform the appropriate logic for the button that the user clicked.

The following example shows how you can respond to a button click in a GridView control. In the example, a button in a TemplateField column sends the command “AddToCart”. The RowCommand event handler determines which button was clicked. If it was the shopping cart button, the code performs the appropriate logic.

Visual Basic

Protected Sub GridView1_RowCommand(ByVal sender As Object, _
  ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
  If (e.CommandName = "AddToCart") Then
    ' Retrieve the row index stored in the CommandArgument property.
    Dim index As Integer = Convert.ToInt32(e.CommandArgument)
    ' Retrieve the row that contains the button
    ' from the Rows collection.
    Dim row As GridViewRow = GridView1.Rows(index)
    ' Add code here to add the item to the shopping cart.
  End If
End Sub

C#

protected void GridView1_RowCommand(object sender,
  GridViewCommandEventArgs e)
{
  if (e.CommandName == "AddToCart")
  {
    // Retrieve the row index stored in the
    // CommandArgument property.
    int index = Convert.ToInt32(e.CommandArgument);

    // Retrieve the row that contains the button
    // from the Rows collection.
    GridViewRow row = GridView1.Rows[index];

    // Add code here to add the item to the shopping cart.
  }
  }

For an example that uses the ButtonField class, see the GridView..::.RowCommand event documentation.

GridView…:: .RowCommand Event

Occurs when a button is clicked in a GridView control

Namespace: System.Web.UI.WebControls

Assembly: System.Web (in System.Web.dll)

Visual Basic (Declaration)

Public Event RowCommand As GridViewCommandEventHandler

Visual Basic (Usage)

Dim instance As GridView

Dim handler As GridViewCommandEventHandler

AddHandler instance.RowCommand, handler

C#

public event GridViewCommandEventHandler RowCommand

Visual C++

public:

event GridViewCommandEventHandler^ RowCommand {

void add (GridViewCommandEventHandler^ value);

void remove (GridViewCommandEventHandler^ value);

}

JScript

JScript does not support events.

ASP.NET

<asp:GridView OnRowCommand=”GridViewCommandEventHandler” />

The RowCommand event is raised when a button is clicked in the GridView control. This enables you to provide an event-handling method that performs a custom routine whenever this event occurs.

Buttons within a GridView control can also invoke some of the built-in functionality of the control. To perform one of these operations, set the CommandName property of a button to one of the values in the following table.

CommandName value Description
“Cancel” Cancels an edit operation and returns the GridView control to read-only mode. Raises the RowCancelingEdit event.
“Delete” Deletes the current record. Raises the RowDeleting and RowDeleted events.
“Edit” Puts the current record in edit mode. Raises the RowEditing event.
“Page” Performs a paging operation. Sets the CommandArgument property of the button to “First”, “Last”, “Next”, “Prev”, or a page number to specify the type of paging operation to perform. Raises the PageIndexChanging and PageIndexChanged events.
“Select” Selects the current record. Raises the SelectedIndexChanging and SelectedIndexChanged events.
“Sort” Sorts the GridView control. Raises the Sorting and Sorted events.
“Update” Updates the current record in the data source. Raises the RowUpdating and RowUpdated events.

Although the RowCommand event is raised when a button listed in the previous table is clicked, it is recommended that you use the events listed in the table for the operation.

A GridViewCommandEventArgs object is passed to the event-handling method, which enables you to determine the command name and command argument of the button clicked.

Note:
To determine the index of the row that raised the event, use the CommandArgument property of the event argument that is passed to the event. The ButtonField class automatically populates the CommandArgument property with the appropriate index value. For other command buttons, you must manually set the CommandArgument property of the command button. For example, you can set the CommandArgument to <%# Container.DataItemIndex %> when the GridView control has no paging enabled.

Examples

The following example demonstrates how to use the RowCommand event to add the name of a customer from a GridView control to a ListBox control when a row’s Add button is clicked.

Visual Basic

<%@ Page language=”VB” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<script runat=”server”>

Sub ContactsGridView_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)

‘ If multiple buttons are used in a GridView control, use the

‘ CommandName property to determine which button was clicked.

If e.CommandName = “Add” Then

‘ Convert the row index stored in the CommandArgument

‘ property to an Integer.

Dim index As Integer = Convert.ToInt32(e.CommandArgument)

‘ Retrieve the row that contains the button clicked

‘ by the user from the Rows collection.

Dim row As GridViewRow = ContactsGridView.Rows(index)

‘ Create a new ListItem object for the contact in the row.

Dim item As New ListItem()

item.Text = Server.HtmlDecode(row.Cells(2).Text) & ” ” & _

Server.HtmlDecode(row.Cells(3).Text)

‘ If the contact is not already in the ListBox, add the ListItem

‘ object to the Items collection of the ListBox control.

If Not ContactsListBox.Items.Contains(item) Then

ContactsListBox.Items.Add(item)

End If

End If

End Sub

</script>

<html  >

<head id=”Head1″ runat=”server”>

<title>GridView RowCommand Example</title>

</head>

<body>

<form id=”form1″ runat=”server”>

<h3>GridView RowCommand Example</h3>

<table width=”100%”>

<tr>

<td style=”width:50%”>

<asp:gridview id=”ContactsGridView”

datasourceid=”ContactsSource”

allowpaging=”true”

autogeneratecolumns=”false”

onrowcommand=”ContactsGridView_RowCommand”

runat=”server”>

<columns>

<asp:buttonfield buttontype=”Link”

commandname=”Add”

text=”Add”/>

<asp:boundfield datafield=”ContactID”

headertext=”Contact ID”/>

<asp:boundfield datafield=”FirstName”

headertext=”First Name”/>

<asp:boundfield datafield=”LastName”

headertext=”Last Name”/>

</columns>

</asp:gridview>

</td>

<td style=”vertical-align:top; width:50%”>

Contacts: <br/>

<asp:listbox id=”ContactsListBox”

runat=”server” Height=”200px” Width=”200px”/>

</td>

</tr>

</table>

<!– This example uses Microsoft SQL Server and connects    –>

<!– to the AdventureWorks sample database. Use an ASP.NET  –>

<!– expression to retrieve the connection string value     –>

<!– from the Web.config file.                              –>

<asp:sqldatasource id=”ContactsSource”

selectcommand=”Select [ContactID], [FirstName], [LastName] From Person.Contact”

connectionstring=”<%$ ConnectionStrings:AdventureWorks_DataConnectionString%>”

runat=”server”/>

</form>

</body>

</html>

C#

<%@ Page language=”C#” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<script runat=”server”>

void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)

{

// If multiple buttons are used in a GridView control, use the

// CommandName property to determine which button was clicked.

if(e.CommandName==”Add”)

{

// Convert the row index stored in the CommandArgument

// property to an Integer.

int index = Convert.ToInt32(e.CommandArgument);

// Retrieve the row that contains the button clicked

// by the user from the Rows collection.

GridViewRow row = ContactsGridView.Rows[index];

// Create a new ListItem object for the contact in the row.

ListItem item = new ListItem();

item.Text = Server.HtmlDecode(row.Cells[2].Text) + ” ” +

Server.HtmlDecode(row.Cells[3].Text);

// If the contact is not already in the ListBox, add the ListItem

// object to the Items collection of the ListBox control.

if (!ContactsListBox.Items.Contains(item))

{

ContactsListBox.Items.Add(item);

}

}

}

</script>

<html  >

<head runat=”server”>

<title>GridView RowCommand Example</title>

</head>

<body>

<form id=”form1″ runat=”server”>

<h3>GridView RowCommand Example</h3>

<table width=”100%”>

<tr>

<td style=”width:50%”>

<asp:gridview id=”ContactsGridView”

datasourceid=”ContactsSource”

allowpaging=”true”

autogeneratecolumns=”false”

onrowcommand=”ContactsGridView_RowCommand”

runat=”server”>

<columns>

<asp:buttonfield buttontype=”Link”

commandname=”Add”

text=”Add”/>

<asp:boundfield datafield=”ContactID”

headertext=”Contact ID”/>

<asp:boundfield datafield=”FirstName”

headertext=”First Name”/>

<asp:boundfield datafield=”LastName”

headertext=”Last Name”/>

</columns>

</asp:gridview>

</td>

<td style=”vertical-align:top; width:50%”>

Contacts: <br/>

<asp:listbox id=”ContactsListBox”

runat=”server” Height=”200px” Width=”200px”/>

</td>

</tr>

</table>

<!– This example uses Microsoft SQL Server and connects    –>

<!– to the AdventureWorks sample database. Use an ASP.NET  –>

<!– expression to retrieve the connection string value     –>

<!– from the Web.config file.                              –>

<asp:sqldatasource id=”ContactsSource”

selectcommand=”Select [ContactID], [FirstName], [LastName] From Person.Contact”

connectionstring=”<%$ ConnectionStrings:AdventureWorks_DataConnectionString%>”

runat=”server”/>

</form>

</body>

</html>

The following example demonstrates how to use the RowCommand event to update the price of a product when a row’s button is clicked. This example has the paging functionality enabled for the GridView control and sets the CommandArgument property of the Button control to the appropriate row index.

Visual Basic

<%@ Page language=”VB” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<script runat=”server”>

Sub ProductsGridView_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)

‘ If multiple buttons are used in a GridView control, use the

‘ CommandName property to determine which button was clicked.

If e.CommandName = “Increase” Then

‘ Convert the row index stored in the CommandArgument

‘ property to an Integer.

Dim index = Convert.ToInt32(e.CommandArgument)

‘ Retrieve the row that contains the button clicked

‘ by the user from the Rows collection.

Dim row = ProductsGridView.Rows(index)

‘ Calculate the new price.

Dim listPriceTextBox = CType(row.FindControl(“PriceLabel”), Label)

listPriceTextBox.Text = (Convert.ToDouble(listPriceTextBox.Text) * 1.05).ToString()

‘ Update the row.

ProductsGridView.UpdateRow(index, False)

End If

End Sub

</script>

<html  >

<head runat=”server”>

<title>GridView RowCommand Example</title>

</head>

<body>

<form id=”form1″ runat=”server”>

<h3>GridView RowCommand Example</h3>

<asp:GridView id=”ProductsGridView”

DataSourceID=”ProductsDataSource”

DataKeyNames=”ProductID”

AllowPaging=”True”

OnRowCommand=”ProductsGridView_RowCommand”

AutoGenerateColumns=”False”

runat=”server”>

<Columns>

<asp:BoundField DataField=”Name” HeaderText=”Product Name” />

<asp:BoundField DataField=”ProductNumber” HeaderText=”Product Number” />

<asp:TemplateField HeaderText=”Price”>

<ItemTemplate>

<asp:Label ID=”PriceLabel” runat=”server”

Text='<%# Bind(“ListPrice”) %>’>

</asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField>

<ItemTemplate>

<asp:Button runat=”server” ID=”IncreaseButton”

Text=”Increase Price 5%”

CommandName=”Increase”

CommandArgument=”<%# CType(Container, GridViewRow).RowIndex %>” />

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

<!– This example uses Microsoft SQL Server and connects    –>

<!– to the AdventureWorks sample database. Use an ASP.NET  –>

<!– expression to retrieve the connection string value     –>

<!– from the Web.config file.                              –>

<asp:SqlDataSource id=”ProductsDataSource”

SelectCommand=”SELECT [ProductID], [Name], [ProductNumber], [ListPrice]

FROM Production.Product

WHERE ListPrice &lt;&gt; 0″

UpdateCommand=”UPDATE Production.Product SET [ListPrice] = @ListPrice

WHERE [ProductID] = @ProductID”

ConnectionString=”<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>”

runat=”server” />

</form>

</body>

</html>

C#

<%@ Page language=”C#” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<script runat=”server”>

void ProductsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)

{

// If multiple buttons are used in a GridView control, use the

// CommandName property to determine which button was clicked.

if(e.CommandName==”Increase”)

{

// Convert the row index stored in the CommandArgument

// property to an Integer.

int index = Convert.ToInt32(e.CommandArgument);

// Retrieve the row that contains the button clicked

// by the user from the Rows collection.

GridViewRow row = ProductsGridView.Rows[index];

// Calculate the new price.

Label listPriceTextBox = (Label)row.FindControl(“PriceLabel”);

listPriceTextBox.Text = (Convert.ToDouble(listPriceTextBox.Text) * 1.05).ToString();

// Update the row.

ProductsGridView.UpdateRow(index, false);

}

}

</script>

<html  >

<head runat=”server”>

<title>GridView RowCommand Example</title>

</head>

<body>

<form id=”form1″ runat=”server”>

<h3>GridView RowCommand Example</h3>

<asp:GridView id=”ProductsGridView”

DataSourceID=”ProductsDataSource”

DataKeyNames=”ProductID”

AllowPaging=”True”

OnRowCommand=”ProductsGridView_RowCommand”

AutoGenerateColumns=”False”

runat=”server”>

<Columns>

<asp:BoundField DataField=”Name” HeaderText=”Product Name” />

<asp:BoundField DataField=”ProductNumber” HeaderText=”Product Number” />

<asp:TemplateField HeaderText=”Price”>

<ItemTemplate>

<asp:Label ID=”PriceLabel” runat=”server”

Text='<%# Bind(“ListPrice”) %>’>

</asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField>

<ItemTemplate>

<asp:Button runat=”server” ID=”IncreaseButton”

Text=”Increase Price 5%”

CommandName=”Increase”

CommandArgument=”<%# ((GridViewRow) Container).RowIndex %>” />

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

<!– This example uses Microsoft SQL Server and connects    –>

<!– to the AdventureWorks sample database. Use an ASP.NET  –>

<!– expression to retrieve the connection string value     –>

<!– from the Web.config file.                              –>

<asp:SqlDataSource id=”ProductsDataSource”

SelectCommand=”SELECT [ProductID], [Name], [ProductNumber], [ListPrice]

FROM Production.Product

WHERE ListPrice &lt;&gt; 0″

UpdateCommand=”UPDATE Production.Product SET [ListPrice] = @ListPrice

WHERE [ProductID] = @ProductID”

ConnectionString=”<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>”

runat=”server” />

</form>

</body>

</html>

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: