GridView.RowCommand 이벤트

정의

GridView 컨트롤에서 단추를 클릭하면 이 이벤트가 발생합니다.

public:
 event System::Web::UI::WebControls::GridViewCommandEventHandler ^ RowCommand;
public event System.Web.UI.WebControls.GridViewCommandEventHandler RowCommand;
member this.RowCommand : System.Web.UI.WebControls.GridViewCommandEventHandler 
Public Custom Event RowCommand As GridViewCommandEventHandler 

이벤트 유형

예제

소스 코드를 사용 하 여 Visual Studio 웹 사이트 프로젝트는 다음이 항목과 함께 사용할 수 있습니다: 다운로드합니다.

다음 예제에서는 사용 하는 RowCommand 방법에 설명 합니다 행의 추가 단추를 클릭할 때 컨트롤에서 GridView 고객의 이름을 추가 하는 ListBox 이벤트입니다.


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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 xmlns="http://www.w3.org/1999/xhtml" >
  <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>

<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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 xmlns="http://www.w3.org/1999/xhtml" >
  <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>

다음 예에서는 행의 단추를 클릭할 때 이벤트를 사용하여 RowCommand 제품 가격을 업데이트하는 방법을 보여 줍니다. 이 예제에서는 컨트롤에 대해 GridView 페이징 기능을 사용하도록 설정하고 컨트롤의 Button 속성을 적절한 행 인덱스로 설정합니다CommandArgument.


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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 xmlns="http://www.w3.org/1999/xhtml" >
  <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 <> 0"
        UpdateCommand="UPDATE Production.Product SET [ListPrice] = @ListPrice 
          WHERE [ProductID] = @ProductID"
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
        runat="server" />

    </form>
  </body>
</html>

<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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 xmlns="http://www.w3.org/1999/xhtml" >
  <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 <> 0"
        UpdateCommand="UPDATE Production.Product SET [ListPrice] = @ListPrice 
          WHERE [ProductID] = @ProductID"
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
        runat="server" />

    </form>
  </body>
</html>

설명

컨트롤 RowCommand 에서 단추를 클릭하면 이벤트가 발생합니다 GridView . 이 옵션을 사용 하면이 이벤트가 발생할 때마다 사용자 지정 루틴을 수행 하는 이벤트 처리 메서드를 제공할 수 있습니다.

내에서 단추를 GridView 컨트롤 컨트롤의 기본 기능 중 일부를 호출할 수도 있습니다. 이러한 작업 중 하나를 수행 하려면 설정의 CommandName 다음 표의 값 중 하나에 단추의 속성입니다.

CommandName Description
"취소" 편집 작업을 취소하고 컨트롤을 GridView 읽기 전용 모드로 반환합니다. RowCancelingEdit 이벤트를 발생시킵니다.
"Delete" 현재 레코드를 삭제합니다. 발생 합니다 RowDeletingRowDeleted 이벤트입니다.
"Edit" 현재 레코드를 편집 모드로 전환합니다. RowEditing 이벤트를 발생시킵니다.
"Page" 페이징 작업을 수행합니다. CommandArgument 단추의 속성을 "First", "Last", "Next", "Prev" 또는 페이지 번호로 설정하여 수행할 페이징 작업의 유형을 지정합니다. 발생 합니다 PageIndexChangingPageIndexChanged 이벤트입니다.
"Select" 현재 레코드를 선택합니다. 발생 합니다 SelectedIndexChangingSelectedIndexChanged 이벤트입니다.
"정렬" 컨트롤을 정렬합니다 GridView . 발생 합니다 SortingSorted 이벤트입니다.
"업데이트" 데이터 소스의 현재 레코드를 업데이트합니다. 발생 합니다 RowUpdatingRowUpdated 이벤트입니다.

하지만 RowCommand 이전 표에 나열 된 단추가 클릭 될 때 이벤트가 발생, 작업에 대 한 테이블에 나열 된 이벤트를 사용 하는 것이 좋습니다.

GridViewCommandEventArgs 개체가 이벤트 처리 메서드에 전달되므로 클릭한 단추의 명령 이름과 명령 인수를 확인할 수 있습니다.

참고

이벤트를 발생시킨 행의 인덱스는 이벤트에 전달되는 이벤트 인수의 속성을 사용합니다 CommandArgument . ButtonField 클래스를 자동으로 채우려고는 CommandArgument 적절 한 인덱스 값을 가진 속성입니다. 다른 명령 단추의 경우 명령 단추의 CommandArgument 속성을 수동으로 설정해야 합니다. 예를 들어 컨트롤에 페이징을 CommandArgument<%# Container.DataItemIndex %> 사용하도록 설정하지 않은 경우 를 GridView 로 설정할 수 있습니다.

이벤트를 처리 하는 방법에 대 한 자세한 내용은 참조 하세요. 이벤트 처리 및 발생합니다.

적용 대상

추가 정보