ButtonField.CommandName Свойство

Определение

Получает или задает строку, представляющую действие, выполняемое при нажатии кнопки в объекте ButtonField.

public:
 virtual property System::String ^ CommandName { System::String ^ get(); void set(System::String ^ value); };
public virtual string CommandName { get; set; }
member this.CommandName : string with get, set
Public Overridable Property CommandName As String

Значение свойства

Имя действия, выполняемого при нажатии на кнопку в ButtonField.

Примеры

В следующем примере кода показано, как использовать CommandName свойство для указания имени команды для кнопок в ButtonField объекте GridView элемента управления .


<%@ 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 CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
  {
  
    // If multiple ButtonField column fields are used, use the
    // CommandName property to determine which button was clicked.
    if(e.CommandName=="Select")
    {
    
      // Convert the row index stored in the CommandArgument
      // property to an Integer.
      int index = Convert.ToInt32(e.CommandArgument);    
    
      // Get the last name of the selected author from the appropriate
      // cell in the GridView control.
      GridViewRow selectedRow = CustomersGridView.Rows[index];
      TableCell contactName = selectedRow.Cells[1];
      string contact = contactName.Text;  
    
      // Display the selected author.
      Message.Text = "You selected " + contact + ".";
      
    }
    
  }
    
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ButtonField Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>ButtonField Example</h3>
      
      <asp:label id="Message"
        forecolor="Red"
        runat="server"
        AssociatedControlID="CustomersGridView"/>
                    
      <!-- Populate the Columns collection declaratively. -->
      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="false"
        onrowcommand="CustomersGridView_RowCommand"
        runat="server">
                
        <columns>
                
          <asp:buttonfield buttontype="Button" 
            commandname="Select"
            headertext="Select Customer" 
            text="Select"/>
          <asp:boundfield datafield="CompanyName" 
            headertext="Company Name"/>
          <asp:boundfield datafield="ContactName" 
            headertext="Contact Name"/>
                
        </columns>
                
      </asp:gridview>
            
        <!-- This example uses Microsoft SQL Server and connects -->
        <!-- to the Northwind sample database.                   -->
        <asp:sqldatasource id="CustomersSqlDataSource"  
          selectcommand="Select [CustomerID], [CompanyName], [ContactName], [ContactTitle] From [Customers]"
          connectionstring="<%$ ConnectionStrings:NorthWindConnection%>"
          runat="server">
        </asp:sqldatasource>
            
    </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 CustomersGridView_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
  
        ' If multiple ButtonField column fields are used, use the
        ' CommandName property to determine which button was clicked.
        If e.CommandName = "Select" Then
    
            ' Convert the row index stored in the CommandArgument
            ' property to an Integer.
            Dim index As Integer = Convert.ToInt32(e.CommandArgument)
    
            ' Get the last name of the selected author from the appropriate
            ' cell in the GridView control.
            Dim selectedRow As GridViewRow = CustomersGridView.Rows(index)
            Dim contactCell As TableCell = selectedRow.Cells(1)
            Dim contact As String = contactCell.Text
    
            ' Display the selected author.
            Message.Text = "You selected " & contact & "."
      
        End If
    
    End Sub
    
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ButtonField Example</title>
</head>
<body>
    <form id="Form1" runat="server">
        
      <h3>ButtonField Example</h3>
      
      <asp:label id="Message"
        forecolor="Red"
        runat="server"
        AssociatedControlID="CustomersGridView"/>
                    
      <!-- Populate the Columns collection declaratively. -->
      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSqlDataSource" 
        autogeneratecolumns="false"
        onrowcommand="CustomersGridView_RowCommand"
        runat="server">
                
        <columns>
                
          <asp:buttonfield buttontype="Button" 
            commandname="Select"
            headertext="Select Customer" 
            text="Select"/>
          <asp:boundfield datafield="CompanyName" 
            headertext="Company Name"/>
          <asp:boundfield datafield="ContactName" 
            headertext="Contact Name"/>
                
        </columns>
                
      </asp:gridview>
            
        <!-- This example uses Microsoft SQL Server and connects -->
        <!-- to the Northwind sample database.                   -->
        <asp:sqldatasource id="CustomersSqlDataSource"  
          selectcommand="Select [CustomerID], [CompanyName], [ContactName], [ContactTitle] From [Customers]"
          connectionstring="<%$ ConnectionStrings:NorthWindConnection%>"
          runat="server">
        </asp:sqldatasource>
            
    </form>
  </body>
</html>

Комментарии

Используйте свойство , CommandName чтобы связать имя команды, например "Add" или "Remove", с кнопками в объекте ButtonField . Для свойства можно задать CommandName любую строку, определяющую действие, выполняемое при нажатии кнопки. Затем можно программно определить имя команды в обработчике событий и выполнить соответствующие действия.

Примечание

Все кнопки в объекте ButtonField имеют одно и то же имя команды.

Элементы управления с привязкой к данным распознают определенные имена команд и автоматически вызывают и обрабатывают соответствующие события для элемента управления. Распознаются следующие имена команд:

  • "Cancel"

  • "Delete"

  • "Edit"

  • "Insert"

  • "New"

  • "Page"

  • "Select"

  • "Sort"

  • "Update"

Чтобы вызвать разбиение по страницам, присвойте параметру CommandName значение ButtonCommandArgument"Page""First", "Last", "Prev""Next"или номеру страницы. Однако, так как CommandArgument для ButtonField элемента управления всегда является целочисленным индексом ButtonField строки, элемент управления не подходит для вызова разбиения по страницам. Аналогичным образом, хотя можно вызвать сортировку, задав для CommandName параметра значение "Sort", CommandArgument свойство для элемента управления всегда является целочисленным индексом ButtonField строки. По этой причине ButtonField элемент управления не подходит для вызова сортировки. Для пользовательских имен команд, таких как "Add" и "Remove", необходимо написать код события, чтобы проверить имя команды и выполнить некоторые настраиваемые действия. Для получения дополнительной информации см. DataControlCommands.

Примечание

Не все имена команд распознаются всеми элементами управления с привязкой к данным. Например, "New" не распознается элементом GridView управления и "Select" не распознается элементом DetailsView управления .

Значение этого свойства хранится в состоянии представления.

Применяется к