2010-08-09 12 views

Respuesta

14

Establezca su fuente de datos para el tipo de objeto que está vinculando a la vista de cuadrícula con un objeto lleno de valores vacíos, luego oculte ese DataRow.

EDIT: Dado que está utilizando una tabla de datos ...

DataTable dt = new DataTable(); 

// Define all of the columns you are binding in your GridView 
dt.Columns.Add("AColumnName"); 
... 
... 

DataRow dr = dt.NewRow(); 
dt.Rows.Add(dr); 

myGridView.DataSource = dt; 
myGridView.DataBind(); 
+0

Estoy utilizando una tabla de datos, ¿tiene alguna muestra? –

+0

Actualizado mi respuesta. – TheGeekYouNeed

+3

Siento que esto es un poco torpe pero me estaba quedando sin tiempo, así que esta solución funcionó para mí. Tuve que ocultar esa fila "vacía" en la vista de cuadrícula al agregar myGridView.Rows [0] .visible = false. – marty

9

más elegante .. extender GridView y añadir una propiedad ShowFooterWhenEmpty de modo que usted no tiene que poner en práctica un código personalizado en todas partes.

Imports System.Web.UI.WebControls 
Imports System.ComponentModel 

Namespace UI.WebControls 
Public Class GridViewExtended 
    Inherits GridView 

    Private _footerRow As GridViewRow 

    <DefaultValue(False), Category("Appearance"), Description("Include the footer when the table is empty")> _ 
    Property ShowFooterWhenEmpty As Boolean 

    <DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(False)> _ 
    Public Overrides ReadOnly Property FooterRow As GridViewRow 
     Get 
      If (Me._footerRow Is Nothing) Then 
       Me.EnsureChildControls() 
      End If 
      Return Me._footerRow 
     End Get 
    End Property 

    Protected Overrides Function CreateChildControls(ByVal dataSource As System.Collections.IEnumerable, ByVal dataBinding As Boolean) As Integer 
     Dim returnVal As Integer = MyBase.CreateChildControls(dataSource, dataBinding) 
     If returnVal = 0 AndAlso Me.ShowFooterWhenEmpty Then 
      Dim table As Table = Me.Controls.OfType(Of Table)().First 
      Me._footerRow = Me.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal, dataBinding, Nothing, Me.Columns.Cast(Of DataControlField).ToArray, table.Rows, Nothing) 
      If Not Me.ShowFooter Then 
       _footerRow.Visible = False 
      End If 
     End If 
     Return returnVal 
    End Function 

    Private Overloads Function CreateRow(ByVal rowIndex As Integer, ByVal dataSourceIndex As Integer, ByVal rowType As DataControlRowType, ByVal rowState As DataControlRowState, ByVal dataBind As Boolean, ByVal dataItem As Object, ByVal fields As DataControlField(), ByVal rows As TableRowCollection, ByVal pagedDataSource As PagedDataSource) As GridViewRow 
     Dim row As GridViewRow = Me.CreateRow(rowIndex, dataSourceIndex, rowType, rowState) 
     Dim e As New GridViewRowEventArgs(row) 
     If (rowType <> DataControlRowType.Pager) Then 
      Me.InitializeRow(row, fields) 
     Else 
      Me.InitializePager(row, fields.Length, pagedDataSource) 
     End If 
     If dataBind Then 
      row.DataItem = dataItem 
     End If 
     Me.OnRowCreated(e) 
     rows.Add(row) 
     If dataBind Then 
      row.DataBind() 
      Me.OnRowDataBound(e) 
      row.DataItem = Nothing 
     End If 
     Return row 
    End Function 

End Class 
End Namespace 
+1

C# versión http://stackoverflow.com/questions/994895/always-show-footertemplate-even-no-data/10891744#10891744 – Aximili

3

Otra solución es añadir siempre una fila ficticia en su fuente de datos, "marca" que fila con un valor específico, entonces ocultar la fila en RowDataBound.

Para ser más precisos, agregue la columna "0 AS dummyRow" al final de la cláusula SELECT de la consulta, a continuación, UNION ALL del DECLARACIÓN completo a

SELECT NULL AS column1, NULL AS column2,...,NULL AS columnN, 1 AS dummyRow 

Una vez que tenga la consulta en su lugar (todos lo que se puede hacer dentro de su SQLDataSource o en el de su objeto DAL, el código de la red se verá algo como esto:

Protected Sub MyGridView_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles MyGridView.RowDataBound 
    If (e.Row.RowType = DataControlRowType.DataRow) AndAlso (Not e.Row.DataItem Is Nothing) AndAlso (CInt(e.Row.DataItem("dummyRow")) = 1) Then 
      e.Row.Visible = False 
    End If 
End Sub 

esta solución viene con algo de sobrecarga obvio, ya que esta comprobación se hará por cada fila de los resultados, sin mencionar que tiene que cambiar su SELECT Q Por supuesto, pero también tiene la ventaja de no requerir cambiar dinámicamente el conjunto de datos (como en el primer ejemplo) y no requerir mucho código o tener que implementar bibliotecas de control personalizadas para su proyecto web.

1

Como nota adicional, si desea condicionalmente mostrar el encabezado y el pie de página de la cuadrícula O mostrar el texto/plantilla de datos vacíos, después de haber ocultado la fila con el código que publiqué anteriormente, puede verificar su condición y si es necesario eliminar la fila. A continuación, el código se verá algo como esto:

Protected Sub MyGridView_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles MyGridView.RowDataBound 
     If (e.Row.RowType = DataControlRowType.DataRow) AndAlso (Not e.Row.DataItem Is Nothing) AndAlso (CInt(e.Row.DataItem("dummyRow")) = 1) Then 
      e.Row.Visible = False 
     If (ConditionToShowEmptyDataTemplate) Then 
      CType(e.Row.DataItem, System.Data.DataRowView).Delete() 
      CType(e.Row.Parent, System.Web.UI.WebControls.Table).Rows.Remove(e.Row) 
     End If 
End Sub 

en cuenta que aquí quitamos tanto la fila DataItem (necesario porque en el post-respalda el gridview puede dibujarse sin re-enlace de datos) y el propio GridView Fila (necesario porque en este punto, la fila ya está en la tabla de Childtable, que no queremos).

Finalmente, si el registro oculto está causando otros problemas en su vista de cuadrícula cuando tiene otros datos (por ejemplo, mala localización), puede usar un código similar para eliminar su fila ficticia cuando la vista de cuadrícula tenga más filas.

0

Lo ideal es que solo quiera mostrar la fila ficticia si aún no hay registros en la tabla. A fin de establecer su SelectCommand a algo como esto:

SELECT [ID], Nombre, Apellido, correo electrónico de clientes unión SELECCIONAR 0 [ID], '' Nombre, '' Apellido '', correo electrónico donde 0 en (SELECCIONAR CUENTA (1) de Clientes)

De esta forma si el recuento> 0, la fila ficticia no se devuelve.

Tenga en cuenta que la fila ficticia no tiene una cláusula FROM en ella.

1

Se puede crear una fila de "vacío" y hacerlo invisible:

if (list != null && list.Any()) 
     { 
      gridView.DataSource = list; 
      gridView.DataBind(); 
     } 
     else 
     { 
      MyCustomClass item = new MyCustomClass(){Id = 0, Name = "(No Data Rows)", Active = false}; 
      List<MyCustomClass> l = new List<MyCustomClass>(); 
      l.Add(item); 
      gridView.DataSource = l; 
      gridView.DataBind(); 
      gridView.Rows[0].Visible = false; 
     } 
Cuestiones relacionadas