2009-02-18 19 views

Respuesta

0

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.

+0

Eso hace gridview pero no datagrid. –

+0

Esto es solo una idea. Equivalente a "Usar adaptadores de control" pero con muestras. Porque este paquete es de fuentes abiertas. No mas. –

0

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 
+0

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 ... –

+0

¿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

3

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

+0

Una solución de javascript. ¡Bonito! –

8

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); 
    } 
} 
+0

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; ' –

+0

@JohnAllers ¿Cómo podemos usar esta clase en el existente? ¿Me puede describir ...? –

+2

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

Cuestiones relacionadas