Поделиться через


ButtonField.DataTextFormatString Свойство

Определение

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

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

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

Строка формата, указывающая формат отображения значения поля. Значение по умолчанию — пустая строка (""), указывающая, что к значению поля не применяется специальное форматирование.

Примеры

В следующем примере кода показано, как использовать DataTextFormatString свойство для указания настраиваемого формата отображения значений поля.


<%@ 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 AuthorsGridView_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 = AuthorsGridView.Rows[index];
      TableCell lastNameCell = selectedRow.Cells[1];
      string lastName = lastNameCell.Text;  
    
      // Display the selected author.
      Message.Text = "You selected " + lastName + ".";
      
    }
    
  }
    
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ButtonField DataTextField Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>ButtonField DataTextField Example</h3>
      
      <asp:label id="Message"
        forecolor="Red"
        runat="server"
        AssociatedControlID="AuthorsGridView"/>
                    
      <!-- Set the DataTextField property of the ButtonField -->
      <!-- declaratively. Set the DataTextFormatString       -->
      <!-- property to apply special formatting to the text. -->
      <asp:gridview id="AuthorsGridView" 
        datasourceid="AuthorsSqlDataSource" 
        autogeneratecolumns="false"
        onrowcommand="AuthorsGridView_RowCommand" 
        runat="server">
                
        <columns>
                
          <asp:buttonfield buttontype="Link" 
            commandname="Select"
            headertext="Select Author"
            datatextfield="au_lname"
            datatextformatstring="[{0}]"    
            text="Select"/>
          <asp:boundfield datafield="au_fname" 
            headertext="First Name"/>
                
        </columns>
                
      </asp:gridview>
            
      <!-- This example uses Microsoft SQL Server and connects -->
      <!-- to the Pubs sample database.                        -->
      <asp:sqldatasource id="AuthorsSqlDataSource"  
        selectcommand="SELECT [au_lname], [au_fname] FROM [authors]"
        connectionstring="server=localhost;database=pubs;integrated security=SSPI"
        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 AuthorsGridView_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 = AuthorsGridView.Rows(index)
      Dim lastNameCell As TableCell = selectedRow.Cells(1)
      Dim lastName As String = lastNameCell.Text
    
      ' Display the selected author.
      Message.Text = "You selected " & lastName & "."
      
    End If
    
  End Sub
    
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>ButtonField DataTextField Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>ButtonField DataTextField Example</h3>
      
      <asp:label id="Message"
        forecolor="Red"
        runat="server"
        AssociatedControlID="AuthorsGridView"/>
                    
      <!-- Set the DataTextField property of the ButtonField -->
      <!-- declaratively. Set the DataTextFormatString       -->
      <!-- property to apply special formatting to the text. -->
      <asp:gridview id="AuthorsGridView" 
        datasourceid="AuthorsSqlDataSource" 
        autogeneratecolumns="false"
        onrowcommand="AuthorsGridView_RowCommand"
        runat="server">
                
        <columns>
                
          <asp:buttonfield buttontype="Link" 
            commandname="Select"
            headertext="Select Author"
            datatextfield="au_lname"
            datatextformatstring="[{0}]"    
            text="Select"/>
          <asp:boundfield datafield="au_fname" 
            headertext="First Name"/>
                
        </columns>
                
      </asp:gridview>
            
      <!-- This example uses Microsoft SQL Server and connects -->
      <!-- to the Pubs sample database.                        -->
      <asp:sqldatasource id="AuthorsSqlDataSource"  
        selectcommand="SELECT [au_lname], [au_fname] FROM [authors]"
        connectionstring="server=localhost;database=pubs;integrated security=SSPI"
        runat="server">
      </asp:sqldatasource>
            
    </form>
  </body>
</html>

Комментарии

DataTextFormatString Используйте свойство, чтобы указать пользовательский формат отображения для значений, отображаемых в объектеButtonField. DataTextFormatString Если свойство не задано, значение поля отображается без специального форматирования.

Замечание

Строка формата применяется только в том случае, если DataTextField свойство задано.

Строка формата может быть любой литеральной строкой и обычно содержит заполнитель для значения поля. Например, в строке "Item Value: {0}"{0} форматирования заполнитель заменяется значением поля при отображении в объектеButtonField. Остальная часть строки форматирования отображается в виде литерального текста.

Замечание

Если строка форматирования не включает заполнитель, значение поля из источника данных не включается в окончательный отображаемый текст.

Заполнитель состоит из двух частей, разделенных двоеточием и завернутыми в фигурные скобки, в форме { : ABxx }. Значение перед двоеточием (A в общем примере) указывает индекс значения поля в списке параметров от нуля.

Замечание

Этот A параметр является частью синтаксиса форматирования. Так как в каждой ячейке имеется только одно значение поля, это значение может быть задано только в 0.

Двоеточие и значения после двоеточия являются необязательными. Символ после двоеточия (B в общем примере) указывает формат, в котором будет отображаться значение. В следующей таблице перечислены распространенные форматы.

Формат символа Описание
C Отображает числовые значения в формате валюты.
D Отображает числовые значения в десятичном формате.
E Отображает числовые значения в формате экспоненциального формата.
F Отображает числовые значения в фиксированном формате.
G Отображает числовые значения в общем формате.
N Отображает числовые значения в формате чисел.
X Отображает числовые значения в шестнадцатеричном формате.

Замечание

XКроме того, символы формата не учитывает регистр. Символ X формата отображает шестнадцатеричные символы в указанном случае.

Значение после символа формата (xx в общем примере) указывает количество значимых цифр или десятичных разрядов для отображения. Например, строка "{0:F2}" формата отображает число фиксированной точки с двумя десятичными разрядами.

Дополнительные сведения о форматировании строк см. в разделе "Типы форматирования".

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

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

См. также раздел