您的位置:首页 > 其它

重写GridView支持数据筛选和自动排序功能

2011-12-12 15:34 441 查看
控件使用方法:

1.在页面Page_Load()方法的!Page.IsPostBack外面重新绑定数据源,即为DataSource赋值,因为页面回传时!Page.IsPostBack内的方法不会执行,先前赋值的DataSource为null。

2.将AllowSelecting属性设置为true

3.将AllowSorting属性设置为true,并为SortExpression赋值

筛选数据前图:





回车,筛选数据后图:





实现代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;
using System.Reflection;
using System.Drawing.Design;

namespace WebCustomControls
{
public class SupperGridView : System.Web.UI.WebControls.GridView
{
private Dictionary<string, string> dic = new Dictionary<string, string>();
private GridViewRow selectorRow;

public SupperGridView()
: base()
{ }

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),Browsable(false)]
public GridViewRow SelectorRow
{
get
{
if (selectorRow == null)
{
this.EnsureChildControls();
}
return this.selectorRow;
}
}

[DefaultValue(false)]
public bool AllowSelecting
{
get
{
object o = ViewState["Selecting"];

if (o != null)
{
return (bool)o;
}
return false;
}
set
{
ViewState["Selecting"] = value;
}
}

protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
{
int num= base.CreateChildControls(dataSource, dataBinding);

if (dataSource != null && AllowSelecting)
{
CreateSelectedRow();
}

return num;
}

// 创建数据筛选行
protected virtual void CreateSelectedRow()
{
if (this.Controls.Count != 0)
{
dic.Clear();
Table table = (Table)this.Controls[0];
TableRowCollection rows = table.Rows;
selectorRow = CreateRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
selectorRow.ID = "SelectRow";
TableCellCollection cells = selectorRow.Cells;

for (int i = 0; i < Columns.Count; i++)
{
TableCell cell = new TableCell();
TextBox box = new TextBox();
box.ID = "box" + i;
box.BorderStyle = BorderStyle.None;
box.AutoPostBack = true;
box.TextChanged += new EventHandler(box_TextChanged);

cell.Controls.Add(box);
cells.AddAt(i, cell);
dic.Add(box.ID, Columns[i].HeaderText);
}
rows.AddAt(1, selectorRow);
}
}

private void box_TextChanged(object sender, EventArgs e)
{
if (DataSource == null) return;

TextBox box = (TextBox)sender;
DataTable table = SelectDataFromTextBox(box);

if (table.Rows.Count == 0)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), this.GetType().FullName, "alert('对不起,没有您搜索的记录!')", true);
return;
}

DataSource = table;
DataBind();
}

//筛选数据逻辑,用linq实现可能给方便
protected virtual DataTable SelectDataFromTextBox(TextBox box)
{
DataTable oldTable = ConvertToDataTable(GetData());
DataTable newTable = oldTable.Clone();
DataRow[] rows = null;
Type columnDataType = oldTable.Columns[dic[box.ID]].DataType;

// Column.DataType是string类型
if (columnDataType == typeof(string))
{
rows = oldTable.Select("" + dic[box.ID] + " like '%" + box.Text + "%'");
}
// Column.DataType非string类型
else
{
rows = oldTable.Select("" + dic[box.ID] + "='" + box.Text + "'");
}

foreach (DataRow row in rows)
{
newTable.Rows.Add(row.ItemArray);
}
return newTable;
}

//将IEnumerable数据类型转换成DataTable数据类型
protected virtual DataTable ConvertToDataTable(IEnumerable data)
{
DataTable dtReturn = new DataTable();

foreach (object item in data)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(item);

foreach (PropertyDescriptor p in props)
{
if (!dtReturn.Columns.Contains(p.Name))
{
dtReturn.Columns.Add(new DataColumn(p.Name, p.PropertyType));
}
}

DataRow row = dtReturn.NewRow();

foreach (PropertyDescriptor p in props)
{
row[p.Name] = p.GetValue(item);
}

dtReturn.Rows.Add(row);
}
return dtReturn;
}

//获取数据源,覆盖并重新实现父类方法
protected  new IEnumerable GetData()
{
DataSourceView dataSourceView = base.GetData();
Type type = dataSourceView.GetType();
MethodInfo method = type.GetMethod("ExecuteSelect", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

if (method == null) return null;

object[] args = new object[] { DataSourceSelectArguments.Empty };
object result = method.Invoke(dataSourceView, args);

return (IEnumerable)result;
}

//为数据筛选行添加样式
protected override void PrepareControlHierarchy()
{
base.PrepareControlHierarchy();

if (this.Controls.Count != 0)
{
foreach (TableCell cell in selectorRow.Cells)
{
if (cell != null && HeaderStyle != null)
{
cell.MergeStyle(HeaderStyle);
}
}
}
}

//重写排序方法
protected override void OnSorting(GridViewSortEventArgs e)
{
base.OnSorting(e);

if (DataSource == null) return;

DataView dataView = ConvertToDataTable(GetData()).DefaultView;

ViewState["sortexpression"] = e.SortExpression;

if (ViewState["sortdirection"] == null)
{
ViewState["sortdirection"] = "asc";
}
else
{
if (ViewState["sortdirection"].ToString() == "asc")
{
ViewState["sortdirection"] = "desc";
}
else
{
ViewState["sortdirection"] = "asc";
}
}

if (ViewState["sortexpression"] != null)
{
dataView.Sort = ViewState["sortexpression"].ToString() + " " + ViewState["sortdirection"].ToString();
}

DataSource = dataView;
DataBind();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐