日期:2014-05-17 浏览次数:20620 次
//绑定的方法
using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Web.UI.WebControls;
using Wuqi.Webdiyer;
public class GridviewControl
{
//当Gridview数据为空时显示的信息
private static string EmptyText = "没有记录";
public GridviewControl()
{
}
/// <summary>
/// 防止PostBack后Gridview不能显示
/// </summary>
/// <param name="gridview"></param>
public static void ResetGridView(GridView gridview)
{
//如果数据为空则重新构造Gridview
if (gridview.Rows.Count == 1 && gridview.Rows[0].Cells[0].Text == EmptyText)
{
int columnCount = gridview.Columns.Count;
gridview.Rows[0].Cells.Clear();
gridview.Rows[0].Cells.Add(new TableCell());
gridview.Rows[0].Cells[0].ColumnSpan = columnCount;
gridview.Rows[0].Cells[0].Text = EmptyText;
gridview.Rows[0].Cells[0].Style.Add("text-align", "center");
}
}
/// <summary>
/// 绑定数据到GridView,当表格数据为空时显示表头
/// </summary>
/// <param name="gridview"></param>
/// <param name="table"></param>
public static void GridViewDataBind(GridView gridview, DataTable table,AspNetPager pager)
{
//记录为空重新构造Gridview
if (table.Rows.Count == 0)
{
table = table.Clone();
table.Rows.Add(table.NewRow());
gridview.DataSource = table;
gridview.DataBind();
int columnCount = gridview.Columns.Count;
gridview.Rows[0].Cells.Clear();
gridview.Rows[0].Cells.Add(new TableCell());
gridview.Rows[0].Cells[0].ColumnSpan = columnCount;
gridview.Rows[0].Cells[0].Text = EmptyText;
gridview.Rows[0].Cells[0].Style.Add("text-align", "center");
pager.Visible = false;
}
else
{
//数据不为空直接绑定
/*--绑定分页--*/
PagedDataSource pds = new PagedDataSource();
pds.DataSource = table.DefaultView;//设置分页的数据源
pager.RecordCount = pds.Count;//AspNetPager1.RecordCount = ds.Tables[0].DefaultView.Count;等价//获取数据的条数
pds.AllowPaging = true;//设置允许分页
pds.CurrentPageIndex = pager.CurrentPageIndex - 1;//设置当前页的索引
pds.PageSize = pager.PageSize;//设置每页显示的页数
pager.CustomInfoHTML = string.Format("当前第<span style='color:red'>{0}</span>/{1}页 共<span style='color:red'>{2}</span>条记录 每页<span style='color:red'>{3}</span>条", new object[] { pager.CurrentPageIndex, pager.PageCount, pager.RecordCount, pager.PageSize });
gridview.DataSource = pds;
gridview.DataBind();
pager.Visible = true;
}
//重新绑定取消选择
gridview.SelectedIndex = -1;
}
public static void GridViewDataBind(GridView gridview, DataTable table)
{
//记录为空重新构造Gridview
if (table.Rows.Count == 0)
{
table = table.Clone();
table.Rows.Add(table.NewRow());
gridview.DataSource = table;
gridview.DataBind();
int columnCount = gridview.Columns.Count;
gridview.Rows[0].Cells.Clear();
grid