¿Hay alguna manera de obtener el control DataGrid para representar los elementos HTML tbody y thead?ASP.NET 2.0 - DataGrid con tbody/thead
Respuesta
DataGrid no tiene algo incorporado para satisfacer sus necesidades. Eche un vistazo al ASP.NET 2.0 CSS Friendly Control Adapters 1.0 que tienen soporte integrado para DataView, pero parece que puede adoptar fácilmente esta idea para DataGrid.
Correcto, parece que la cuadrícula de datos no es compatible de esta forma, así que tuve que crear una clase que hereda de DataGrid. Después de que DataGrid haya renderizado, entonces analizo el HTML e inyecto los elementos en el lugar correcto.
Se adjunta mi clase para aquellos que quieren saber cómo. Este es un enfoque rápido y sucio, por lo que soy bienvenido a mejores ideas.
Imports System.IO
Imports System.Text
Public Class TestDataGrid
Inherits System.Web.UI.WebControls.DataGrid
Private sTHeadClass As String = String.Empty
Private sTBodyClass As String = String.Empty
Private sTFootClass As String = String.Empty
#Region " Properties "
Public Property THeadClass() As String
Get
Return sTHeadClass
End Get
Set(ByVal value As String)
sTHeadClass = value
End Set
End Property
Public Property TBodyClass() As String
Get
Return sTBodyClass
End Get
Set(ByVal value As String)
sTBodyClass = value
End Set
End Property
Public Property TFootClass() As String
Get
Return sTFootClass
End Get
Set(ByVal value As String)
sTFootClass = value
End Set
End Property
#End Region
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
Dim oMemoryStream As New MemoryStream()
Dim oStreamWriter As New StreamWriter(oMemoryStream)
Dim oStreamReader As New StreamReader(oMemoryStream)
Dim oHtmlTextWriter As New HtmlTextWriter(oStreamWriter)
MyBase.Render(oHtmlTextWriter)
oHtmlTextWriter.Flush()
oMemoryStream.Flush()
oMemoryStream.Position = 0
Dim sHtml As String = oStreamReader.ReadToEnd()
Dim oHtml As New Text.StringBuilder()
Dim iPastIndex As Integer = 0
Dim iIndex As Integer = sHtml.IndexOf("<tr>")
oHtml.Append(sHtml.Substring(iPastIndex, iIndex - iPastIndex))
iPastIndex = iIndex
If ShowHeader Then
WriteElementStart(oHtml, "thead", sTHeadClass)
'Write Header Row
iIndex = sHtml.IndexOf("</tr>", iPastIndex) + 5
oHtml.Append(sHtml.Substring(iPastIndex, iIndex - iPastIndex))
iPastIndex = iIndex
oHtml.Append("</thead>")
WriteElementStart(oHtml, "tbody", sTBodyClass)
Else
WriteElementStart(oHtml, "tbody", sTBodyClass)
End If
If ShowFooter Then
'Writer Body Rows
iIndex = sHtml.LastIndexOf("<tr>")
oHtml.Append(sHtml.Substring(iPastIndex, iIndex - iPastIndex))
iPastIndex = iIndex
WriteElementEnd(oHtml, "tbody")
WriteElementStart(oHtml, "tfoot", sTFootClass)
'Write Footer Row
iIndex = sHtml.LastIndexOf("</table>")
oHtml.Append(sHtml.Substring(iPastIndex, iIndex - iPastIndex))
iPastIndex = iIndex
WriteElementEnd(oHtml, "tfoot")
Else
iIndex = sHtml.LastIndexOf("</table>")
oHtml.Append(sHtml.Substring(iPastIndex, iIndex - iPastIndex))
iPastIndex = iIndex
WriteElementEnd(oHtml, "tbody")
End If
oHtml.Append(sHtml.Substring(iPastIndex, sHtml.Length - iPastIndex))
writer.Write(oHtml.ToString())
End Sub
Private Sub WriteElementStart(ByVal Builder As StringBuilder, ByVal Tag As String, ByVal CssClass As String)
If String.IsNullOrEmpty(CssClass) Then
Builder.AppendFormat("<{0}>", Tag)
Else
Builder.AppendFormat("<{0} class='{1}'>", Tag, CssClass)
End If
End Sub
Private Sub WriteElementEnd(ByVal Builder As StringBuilder, ByVal Tag As String)
Builder.AppendFormat("</{0}>", Tag)
End Sub
End Class
Lo siento, pero no me gusta esta solución. Por ejemplo, depende de HtmlWriter utilizado. Con UpperCaseHtmlWriter su solución no funcionará. También código con MemoryStream ... También HtmlTextWriter ... –
¿Podría explicarlo más? El método Render del control espera un HtmlTextWriter como entrada, ¡está en la definición! ¿Cuál es su objeción a MemoryStream, etc.? – Ady
Se puede hacer también a través de javascript.
function AddTHEAD(tableName)
{
var table = document.getElementById(tableName);
if(table != null)
{
var head = document.createElement("THEAD");
head.style.display = "table-header-group";
head.appendChild(table.rows[0]);
table.insertBefore(head, table.childNodes[0]);
}
}
A continuación, debe llamar a esta función en el proceso de carga cuerpo así:
<body onload="javascript: AddTHEAD('DataGridId')">
Fuente: http://www.codeproject.com/KB/grid/HeaderOnEachPage.aspx
Una solución de javascript. ¡Bonito! –
Aunque me gusta la respuesta por "user186197", que entrada en el blog utiliza la reflexión, las cosas podría salir mal en entornos de hosting no confiables. Esto es lo que usamos, no hacks:
public class THeadDataGrid : System.Web.UI.WebControls.DataGrid
{
protected override void OnPreRender(EventArgs e)
{
this.UseAccessibleHeader = true; //to make sure we render TH, not TD
Table table = Controls[0] as Table;
if (table != null && table.Rows.Count > 0)
{
table.Rows[0].TableSection = TableRowSection.TableHeader;
table.Rows[table.Rows.Count - 1].TableSection = TableRowSection.TableFooter;
}
base.OnPreRender(e);
}
}
Me gusta esta solución, con algunos cambios menores: 'if (this.ShowHeader) table.Rows [0] .TableSection = TableRowSection.TableHeader;' y 'if (this.ShowFooter) table.Rows [table.Rows.Count - 1] .TableSection = TableRowSection.TableFooter; ' –
@JohnAllers ¿Cómo podemos usar esta clase en el
Si bien esta respuesta funciona y la agradezco mucho, este es el tipo de cosas que me volvieron loco acerca de los formularios web y finalmente me empujaron hacia MVC. – akousmata
- 1. Instale ASP.NET 4.0 junto con ASP.NET 2.0 en IIS6
- 2. ASP.NET 2.0 o 3.5?
- 3. ¿ASP.Net MVC se ejecuta sobre ASP.NET 2.0?
- 4. ¿Qué significa ASP.net versión 2.0?
- 5. Url.Content en ASP.net MVC 2.0
- 6. WPF datagrid con MVVM
- 7. ¿Cómo consigo ninject 2.0 trabajando con asp.net mvc 2?
- 8. Posible crear un servicio web REST con ASP.NET 2.0
- 9. GPL 2.0 Extensiones Telerik para ASP.NET MVC
- 10. ASP.NET 2.0 JQuery AJAX Iniciar sesión
- 11. Instalación de ASP.Net 2.0 después de IIS
- 12. Datagrid vs Gridview
- 13. Recursos para aprender ASP.NET MVC 2.0
- 14. ASP.NET MVC 2.0 JsonRequestBehavior Configuración global
- 15. Estilo WPF DataGrid-Silverlight DataGrid?
- 16. Cómo implementar áreas en ASP.NET MVC 1.0 para ser más compatible con ASP.NET MVC 2.0
- 17. ClassNotFoundException con Guice 2.0
- 18. With.Parameters.ConstructorArgument con ninject 2.0
- 19. SAML con .NET 2.0
- 20. NServiceBus con Unity 2.0?
- 21. WPF DataGrid con alturas de fila variables
- 22. Rendimiento lento con WPF DataGrid y ScrollViewer
- 23. ¿Puedo desarrollar proyectos asp.net 3.5/2.0 usando Visual Studio 2010?
- 24. Cómo forzar a mi aplicación ASP.net 2.0 a recompilar
- 25. Certificado autofirmado con SAML 2.0
- 26. Parse json con gwt 2.0
- 27. ASP.NET 2.0 RijndaelArreglo de cifrado administrado vs. FIPS
- 28. Refactorización de una aplicación ASP.NET 2.0 para ser más "moderna"
- 29. El uso de la API de Bit.ly en ASP.NET 2.0
- 30. asp.net enlace de modelo de moneda MVC 1.0 y 2.0
Eso hace gridview pero no datagrid. –
Esto es solo una idea. Equivalente a "Usar adaptadores de control" pero con muestras. Porque este paquete es de fuentes abiertas. No mas. –