ButtonField.DataTextFormatString Propiedad

Definición

Obtiene o establece la cadena que especifica el formato de presentación del valor del campo.

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

Valor de propiedad

Una cadena de formato que especifica el formato de presentación del valor del campo. El valor predeterminado es una cadena vacía (""), lo que indica que no se aplica ningún formato especial al valor del campo.

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar la DataTextFormatString propiedad para especificar un formato de presentación personalizado para los valores de un campo.


<%@ 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>

Comentarios

Utilice la DataTextFormatString propiedad para especificar un formato de presentación personalizado para los valores que se muestran en el ButtonField objeto . Si no se establece la DataTextFormatString propiedad, el valor del campo se muestra sin ningún formato especial.

Nota:

La cadena de formato solo se aplica cuando se establece la DataTextField propiedad .

La cadena de formato puede ser cualquier cadena literal y normalmente incluye un marcador de posición para el valor del campo. Por ejemplo, en la cadena "Item Value: {0}"de formato , el {0} marcador de posición se reemplaza por el valor del campo cuando se muestra en el ButtonField objeto . El resto de la cadena de formato se muestra como texto literal.

Nota

Si la cadena de formato no incluye un marcador de posición, el valor del campo del origen de datos no se incluye en el texto para mostrar final.

El marcador de posición consta de dos partes, separadas por dos puntos y ajustadas entre llaves, con el formato { A : Bxx }. El valor anterior a los dos puntos (A en el ejemplo general) especifica el índice del valor de campo en una lista de parámetros de base cero.

Nota

Este A parámetro forma parte de la sintaxis de formato. Dado que solo hay un valor de campo en cada celda, este valor solo se puede establecer en 0.

Los dos puntos y los valores después de los dos puntos son opcionales. El carácter después de los dos puntos (B en el ejemplo general) especifica el formato en el que se va a mostrar el valor. En la tabla siguiente se enumeran los formatos comunes.

Carácter de formato Descripción
C Muestra valores numéricos en formato de moneda.
D Muestra valores numéricos en formato decimal.
E Muestra valores numéricos en formato científico (exponencial).
F Muestra valores numéricos en formato fijo.
G Muestra valores numéricos en formato general.
N Muestra valores numéricos en formato numérico.
X Muestra valores numéricos en formato hexadecimal.

Nota

Excepto , Xlos caracteres de formato no distinguen mayúsculas de minúsculas. El X carácter de formato muestra los caracteres hexadecimales en el caso especificado.

El valor después del carácter de formato (xx en el ejemplo general) especifica el número de dígitos significativos o posiciones decimales que se van a mostrar. Por ejemplo, la cadena "{0:F2}" de formato muestra un número de punto fijo con dos posiciones decimales.

Para obtener más información sobre cómo dar formato a las cadenas, vea Tipos de formato.

El valor de esta propiedad se almacena en estado de vista.

Se aplica a

Consulte también