Cumple la función de clase base para todos los tipos de campos de controles de datos que representen una columna de datos en controles enlazados a datos tabulares, como
DetailsView y
GridView.
Espacio de nombres: System.Web.UI.WebControls
Ensamblado: System.Web (en system.web.dll)
Visual Basic (Declaración)
<TypeConverterAttribute(GetType(ExpandableObjectConverter))> _
Public MustInherit Class DataControlField
Implements IStateManager, IDataSourceViewSchemaAccessor
Dim instance As DataControlField
[TypeConverterAttribute(typeof(ExpandableObjectConverter))]
public abstract class DataControlField : IStateManager, IDataSourceViewSchemaAccessor
[TypeConverterAttribute(typeof(ExpandableObjectConverter))]
public ref class DataControlField abstract : IStateManager, IDataSourceViewSchemaAccessor
/** @attribute TypeConverterAttribute(System.ComponentModel.ExpandableObjectConverter) */
public abstract class DataControlField implements IStateManager, IDataSourceViewSchemaAccessor
TypeConverterAttribute(System.ComponentModel.ExpandableObjectConverter)
public abstract class DataControlField implements IStateManager, IDataSourceViewSchemaAccessor
La clase DataControlField cumple la función de clase base para todos los tipos de campos de control de datos. Los campos de controles de datos permiten que los controles enlazados a datos representen un campo de datos, de igual forma que un objeto DataGridColumn representa un tipo de columna en el control DataGrid.
Use las clases derivadas de DataControlField para controlar cómo se muestra un campo de datos en un control enlazado a datos como DetailsView o GridView. En la tabla siguiente se muestran los diferentes tipos de campos de controles de datos proporcionados por ASP.NET.
| Tipo de campo de columna | Descripción |
| BoundField | Muestra el valor de un campo de un origen de datos como texto. |
| ButtonField | Muestra un botón de comando en un control enlazado a datos. Dependiendo del control, esto permite mostrar una fila o una columna con un control de botón personalizado, como un botón Agregar o Quitar. |
| CheckBoxField | Muestra una casilla de verificación en un control enlazado a datos. Este tipo de campo de control de datos se utiliza habitualmente para mostrar campos con un valor booleano. |
| CommandField | Muestra botones de comando integrados que permiten realizar operaciones de edición, inserción o eliminación en un control enlazado a datos. |
| HyperLinkField | Muestra el valor de un campo de un origen de datos como un hipervínculo. Este tipo de campo de control de datos permite enlazar un segundo campo a la dirección URL del hipervínculo. |
| ImageField | Muestra una imagen en un control enlazado a datos. |
| TemplateField | Muestra el contenido definido por el usuario para un control enlazado a datos según una plantilla especificada. |
También puede extender las clases DataControlField y BoundField para crear sus propios tipos de campo de control de datos.
La clase DataControlField proporciona muchas propiedades que determinan cómo se presentan los elementos de la interfaz de usuario en el control enlazado a datos. No todos los controles utilizan todas las propiedades de campo de control de datos disponibles al representar una interfaz de usuario. Por ejemplo, el control DetailsView, que muestra los campos de los controles de datos como filas, incluye un elemento de encabezado para cada campo del control de datos, pero no un elemento de pie de página. El control DetailsView omite, por consiguiente, las propiedades FooterText y FooterStyle. Sin embargo, el control GridView, utiliza las propiedades FooterText y FooterStyle si la propiedad ShowFooter se establece en true. De forma similar, las propiedades de los campos de control de datos afectan a la presentación de los elementos de la interfaz de usuario que dependen de lo que es el elemento. La propiedad ItemStyle siempre se aplica al campo. Si el tipo derivado de DataControlField contiene un control, como en las clases ButtonField o CheckBoxField, la propiedad ControlStyle se aplica al campo.
En el ejemplo de código siguiente se muestra cómo utilizar los objetos BoundField y ButtonField, que se derivan de DataControlField, para mostrar las filas de un control DetailsView. El control DetailsView tiene la propiedad AutoGenerateRows establecida en false, lo que le permite mostrar un subconjunto de los datos devueltos por la propiedad SelectCommand.
<%@ page language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:sqldatasource
id="SqlDataSource1"
runat="server"
connectionstring="<%$ ConnectionStrings:MyNorthwind%>"
selectcommand="Select * From Employees">
</asp:sqldatasource>
<asp:detailsview
id="DetailsView1"
runat="server"
allowpaging="True"
datasourceid="SqlDataSource1"
height="208px"
width="264px"
autogeneraterows="False">
<fields>
<asp:boundfield
sortexpression="LastName"
datafield="LastName"
headertext="LastName">
<itemstyle backcolor="Yellow">
</itemstyle>
</asp:boundfield>
<asp:boundfield
sortexpression="FirstName"
datafield="FirstName"
headertext="FirstName">
<itemstyle forecolor="#C00000">
</itemstyle>
</asp:boundfield>
<asp:buttonfield
text="TestButton"
buttontype="Button">
</asp:buttonfield>
</fields>
</asp:detailsview>
</form>
</body>
</html>
<%@ page language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:sqldatasource
id="SqlDataSource1"
runat="server"
connectionstring="<%$ ConnectionStrings:MyNorthwind%>"
selectcommand="Select * From Employees">
</asp:sqldatasource>
<asp:detailsview
id="DetailsView1"
runat="server"
allowpaging="True"
datasourceid="SqlDataSource1"
height="208px"
width="264px"
autogeneraterows="False">
<fields>
<asp:boundfield
sortexpression="LastName"
datafield="LastName"
headertext="LastName">
<itemstyle backcolor="Yellow">
</itemstyle>
</asp:boundfield>
<asp:boundfield
sortexpression="FirstName"
datafield="FirstName"
headertext="FirstName">
<itemstyle forecolor="#C00000">
</itemstyle>
</asp:boundfield>
<asp:buttonfield
text="TestButton"
buttontype="Button">
</asp:buttonfield>
</fields>
</asp:detailsview>
</form>
</body>
</html>
<%@ page language="VJ#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:sqldatasource
id="SqlDataSource1"
runat="server"
connectionstring="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;"
selectcommand="Select * From Employees">
</asp:sqldatasource>
<asp:detailsview
id="DetailsView1"
runat="server"
allowpaging="True"
datasourceid="SqlDataSource1"
height="208px"
width="264px"
autogeneraterows="False">
<fields>
<asp:boundfield
sortexpression="LastName"
datafield="LastName"
headertext="LastName">
<itemstyle backcolor="Yellow">
</itemstyle>
</asp:boundfield>
<asp:boundfield
sortexpression="FirstName"
datafield="FirstName"
headertext="FirstName">
<itemstyle forecolor="#C00000">
</itemstyle>
</asp:boundfield>
<asp:buttonfield
text="TestButton"
buttontype="Button">
</asp:buttonfield>
</fields>
</asp:detailsview>
</form>
</body>
</html>
En el ejemplo de código siguiente se muestra cómo extender la clase BoundField para crear un campo enlazado personalizado que pueda utilizar el control GridView. Análogamente a la clase CheckBoxField, la clase RadioButtonField representa una columna de datos true o false. No obstante, aunque los datos a los que está enlazada la clase CheckBoxField pueden ser cualquier conjunto de valores true o false, el conjunto de datos a los que está enlazada la clase RadioButtonField sólo puede tener un valor true en cada momento. En este ejemplo se muestra cómo implementar los métodos ExtractValuesFromCell y InitializeCell, dos métodos importantes de todas las clases derivadas de DataControlField.
Imports System
Imports System.Collections.Specialized
Imports System.Collections
Imports System.ComponentModel
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Namespace Samples.AspNet.VB
<AspNetHostingPermission(SecurityAction.Demand, _
Level:=AspNetHostingPermissionLevel.Minimal)> _
Public NotInheritable Class RadioButtonField
Inherits CheckBoxField
Public Sub New()
End Sub 'New
' Gets a default value for a basic design-time experience. Since
' it would look odd, even at design time, to have more than one
' radio button selected, make sure that none are selected.
Protected Overrides Function GetDesignTimeValue() As Object
Return False
End Function
' This method is called by the ExtractRowValues methods of
' GridView and DetailsView. Retrieve the current value of the
' cell from the Checked state of the Radio button.
Public Overrides Sub ExtractValuesFromCell( _
ByVal dictionary As IOrderedDictionary, _
ByVal cell As DataControlFieldCell, _
ByVal rowState As DataControlRowState, _
ByVal includeReadOnly As Boolean)
' Determine whether the cell contain a RadioButton
' in its Controls collection.
If cell.Controls.Count > 0 Then
Dim radio As RadioButton = CType(cell.Controls(0), RadioButton)
Dim checkedValue As Object = Nothing
If radio Is Nothing Then
' A RadioButton is expected, but a null is encountered.
' Add error handling.
Throw New InvalidOperationException( _
"RadioButtonField could not extract control.")
Else
checkedValue = radio.Checked
End If
' Add the value of the Checked attribute of the
' RadioButton to the dictionary.
If dictionary.Contains(DataField) Then
dictionary(DataField) = checkedValue
Else
dictionary.Add(DataField, checkedValue)
End If
End If
End Sub
' This method adds a RadioButton control and any other
' content to the cell's Controls collection.
Protected Overrides Sub InitializeDataCell( _
ByVal cell As DataControlFieldCell, _
ByVal rowState As DataControlRowState)
Dim radio As New RadioButton()
' If the RadioButton is bound to a DataField, add
' the OnDataBindingField method event handler to the
' DataBinding event.
If DataField.Length <> 0 Then
AddHandler radio.DataBinding, AddressOf Me.OnDataBindField
End If
radio.Text = Me.Text
' Because the RadioButtonField is a BoundField, it only
' displays data. Therefore, unless the row is in edit mode,
' the RadioButton is displayed as disabled.
radio.Enabled = False
' If the row is in edit mode, enable the button.
If (rowState And DataControlRowState.Edit) <> 0 _
OrElse (rowState And DataControlRowState.Insert) <> 0 Then
radio.Enabled = True
End If
cell.Controls.Add(radio)
End Sub
End Class
End Namespace
namespace Samples.AspNet.CS {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
[AspNetHostingPermission(SecurityAction.Demand,
Level=AspNetHostingPermissionLevel.Minimal)]
public sealed class RadioButtonField : CheckBoxField {
public RadioButtonField() {
}
// Gets a default value for a basic design-time experience.
// Since it would look odd, even at design time, to have
// more than one radio button selected, make sure that none
// are selected.
protected override object GetDesignTimeValue() {
return false;
}
// This method is called by the ExtractRowValues methods of
// GridView and DetailsView. Retrieve the current value of the
// cell from the Checked state of the Radio button.
public override void ExtractValuesFromCell(IOrderedDictionary dictionary,
DataControlFieldCell cell,
DataControlRowState rowState,
bool includeReadOnly)
{
// Determine whether the cell contains a RadioButton
// in its Controls collection.
if (cell.Controls.Count > 0) {
RadioButton radio = cell.Controls[0] as RadioButton;
object checkedValue = null;
if (null == radio) {
// A RadioButton is expected, but a null is encountered.
// Add error handling.
throw new InvalidOperationException
("RadioButtonField could not extract control.");
}
else {
checkedValue = radio.Checked;
}
// Add the value of the Checked attribute of the
// RadioButton to the dictionary.
if (dictionary.Contains(DataField))
dictionary[DataField] = checkedValue;
else
dictionary.Add(DataField, checkedValue);
}
}
// This method adds a RadioButton control and any other
// content to the cell's Controls collection.
protected override void InitializeDataCell
(DataControlFieldCell cell, DataControlRowState rowState) {
RadioButton radio = new RadioButton();
// If the RadioButton is bound to a DataField, add
// the OnDataBindingField method event handler to the
// DataBinding event.
if (DataField.Length != 0) {
radio.DataBinding += new EventHandler(this.OnDataBindField);
}
radio.Text = this.Text;
// Because the RadioButtonField is a BoundField, it only
// displays data. Therefore, unless the row is in edit mode,
// the RadioButton is displayed as disabled.
radio.Enabled = false;
// If the row is in edit mode, enable the button.
if ((rowState & DataControlRowState.Edit) != 0 ||
(rowState & DataControlRowState.Insert) != 0) {
radio.Enabled = true;
}
cell.Controls.Add(radio);
}
}
}
package Samples.AspNet;
import System.*;
import System.Collections.*;
import System.Collections.Specialized.*;
import System.ComponentModel.*;
import System.Web.UI.*;
import System.Web.UI.WebControls.*;
public class RadioButtonField extends CheckBoxField
{
public RadioButtonField()
{
} //RadioButtonField
// Gets a default value for a basic design-time experience.
//Since it would look odd,
// even at design time, to have more than one radio button selected,
//make sure that
// none are selected.
protected Object GetDesignTimeValue()
{
return (System.Boolean)false;
} //GetDesignTimeValue
// This method is called by the ExtractRowValues methods on GridView
//and DetailsView. Retrieve
// the current value of the cell from the Checked state of the Radio button.
public void ExtractValuesFromCell(IOrderedDictionary dictionary,
DataControlFieldCell cell, DataControlRowState rowState,
boolean includeReadOnly) throws InvalidOperationException
{
// Does the cell contain a RadioButton in its Controls collection?
if (cell.get_Controls().get_Count() > 0) {
RadioButton radio = (RadioButton)cell.get_Controls().get_Item(0);
Object checkedValue = null;
if (null == radio) {
// A RadioButton is expected,
// but a null is encountered. Add error handling.
throw new InvalidOperationException("RadioButtonField could not"
+ "extract control.");
}
else {
checkedValue = (System.Boolean)radio.get_Checked();
}
// Add the value of the Checked attribute of the
// RadioButton to the dictionary.
if (dictionary.Contains(get_DataField())) {
dictionary.set_Item(get_DataField(), checkedValue);
}
else {
dictionary.Add(get_DataField(), checkedValue);
}
}
} //ExtractValuesFromCell
// This method adds a RadioButton control and any other content to the
//cell's Controls collection.
protected void InitializeDataCell(DataControlFieldCell cell,
DataControlRowState rowState)
{
RadioButton radio = new RadioButton();
// If the RadioButton is bound to a DataField, add
// the OnDataBindingField method event handler to the
// DataBinding event.
if (get_DataField().get_Length() != 0) {
radio.add_DataBinding(new EventHandler(this.OnDataBindField));
}
radio.set_Text(this.get_Text());
// Because the RadioButtonField is a BoundField, it only displays data. Therefore,
// unless the row is in edit mode, the RadioButton is displayed as
// disabled.
radio.set_Enabled(false);
// If the row is in edit mode, enable the button.
if (((int)(rowState & DataControlRowState.Edit) != 0) || ((int)(
rowState & DataControlRowState.Insert) != 0)) {
radio.set_Enabled(true);
}
cell.get_Controls().Add(radio);
} //InitializeDataCell
} //RadioButtonField
En el ejemplo de código siguiente se muestra cómo utilizar la clase RadioButtonField, que se proporciona en el ejemplo anterior, en un control GridView. En este ejemplo, el control GridView muestra los datos de un equipo deportivo. Los datos de los jugadores se mantienen en una tabla de datos que incluye una columna de identificador, columnas para los nombres de los jugadores y una columna con un valor de verdadero o falso que identifica al capitán del equipo. La clase RadioButtonField permite mostrar qué miembro del equipo es el capitán del equipo. El control GridView se puede editar para seleccionar a un nuevo capitán o cambiar otra información de los jugadores.
<%@ page language="VB" %>
<%@ Register Tagprefix="aspSample"
Namespace="Samples.AspNet.VB"
Assembly="Samples.AspNet.VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:gridview
id="GridView1"
runat="server"
allowpaging="True"
datasourceid="SqlDataSource1"
allowsorting="True"
autogeneratecolumns="False"
autogenerateeditbutton="True"
datakeynames="AnID">
<columns>
<aspSample:radiobuttonfield
headertext="RadioButtonField"
text="TeamLeader"
datafield="TrueFalse">
</aspSample:radiobuttonfield>
<asp:boundfield
insertvisible="False"
sortexpression="AnID"
datafield="AnID"
readonly="True"
headertext="AnID">
</asp:boundfield>
<asp:boundfield
sortexpression="FirstName"
datafield="FirstName"
headertext="FirstName">
</asp:boundfield>
<asp:boundfield
sortexpression="LastName"
datafield="LastName"
headertext="LastName">
</asp:boundfield>
</columns>
</asp:gridview>
<asp:sqldatasource
id="SqlDataSource1"
runat="server"
connectionstring="<%$ ConnectionStrings:MyNorthwind%>"
selectcommand="SELECT AnID,FirstName,LastName,TeamLeader FROM Players"
updatecommand="UPDATE Players SET TrueFalse='false';UPDATE Players SET TrueFalse='true' WHERE AnID=@anID">
</asp:sqldatasource>
</form>
</body>
</html>
<%@ page language="C#" %>
<%@ Register Tagprefix="aspSample"
Namespace="Samples.AspNet.CS"
Assembly="Samples.AspNet.CS" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:gridview
id="GridView1"
runat="server"
allowpaging="True"
datasourceid="SqlDataSource1"
allowsorting="True"
autogeneratecolumns="False"
autogenerateeditbutton="True"
datakeynames="AnID">
<columns>
<aspSample:radiobuttonfield
headertext="RadioButtonField"
text="TeamLeader"
datafield="TrueFalse">
</aspSample:radiobuttonfield>
<asp:boundfield
insertvisible="False"
sortexpression="AnID"
datafield="AnID"
readonly="True"
headertext="AnID">
</asp:boundfield>
<asp:boundfield
sortexpression="FirstName"
datafield="FirstName"
headertext="FirstName">
</asp:boundfield>
<asp:boundfield
sortexpression="LastName"
datafield="LastName"
headertext="LastName">
</asp:boundfield>
</columns>
</asp:gridview>
<asp:sqldatasource
id="SqlDataSource1"
runat="server"
connectionstring="<%$ ConnectionStrings:MyNorthwind%>"
selectcommand="SELECT AnID,FirstName,LastName,TeamLeader FROM Players"
updatecommand="UPDATE Players SET TrueFalse='false';UPDATE Players SET TrueFalse='true' WHERE AnID=@anID">
</asp:sqldatasource>
</form>
</body>
</html>
<%@ page language="VJ#" %>
<%@ Register Tagprefix="aspSample"
Namespace="Samples.AspNet"
Assembly="Samples.AspNet.JSL" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:gridview
id="GridView1"
runat="server"
allowpaging="True"
datasourceid="SqlDataSource1"
allowsorting="True"
autogeneratecolumns="False"
autogenerateeditbutton="True"
datakeynames="AnID">
<columns>
<aspSample:radiobuttonfield
headertext="RadioButtonField"
text="TeamLeader"
datafield="TrueFalse">
</aspSample:radiobuttonfield>
<asp:boundfield
insertvisible="False"
sortexpression="AnID"
datafield="AnID"
readonly="True"
headertext="AnID">
</asp:boundfield>
<asp:boundfield
sortexpression="FirstName"
datafield="FirstName"
headertext="FirstName">
</asp:boundfield>
<asp:boundfield
sortexpression="LastName"
datafield="LastName"
headertext="LastName">
</asp:boundfield>
</columns>
</asp:gridview>
<asp:sqldatasource
id="SqlDataSource1"
runat="server"
Connectionstring="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind"
SelectCommand="SELECT AnID,FirstName,LastName,TeamLeader FROM Players"
UpdateCommand="UPDATE Players SET TrueFalse='false';UPDATE Players SET TrueFalse='true' WHERE AnID=@anID">
</asp:sqldatasource>
</form>
</body>
</html>
Seguridad de .NET Framework
System.Object
System.Web.UI.WebControls.DataControlField
System.Web.UI.WebControls.BoundField
System.Web.UI.WebControls.ButtonFieldBase
System.Web.UI.WebControls.HyperLinkField
System.Web.UI.WebControls.ImageField
System.Web.UI.WebControls.TemplateField
Seguridad para subprocesos
Los miembros estáticos públicos (Shared en Visual Basic) de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.
Windows 98, Windows 2000 Service Pack 4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter
Microsoft .NET Framework 3.0 es compatible con Windows Vista, Microsoft Windows XP SP2 y Windows Server 2003 SP1.
.NET Framework
Compatible con: 3.0, 2.0