带搜索功能的GridView控件 收藏
Demo代码下载
最近需要一个gridview能够有不错的搜索功能,最好还是个GridView的扩展控件以后可以直接使用。我试着在CSDN上搜了一下下面这两篇文章都是带Search功能的GridView。
http://blog.csdn.net/xiandawang/archive/2007/05/25/1625529.aspx
http://blog.csdn.net/xiandawang/archive/2007/05/25/1625529.aspx
但是它们不是很好。后来终于看到一个SearchGridview控件,挺不错的介绍给大家。
我这直接介绍一下它的实现吧。
1. 写了一个GridView的扩展控件SearchabbleGridView类。
2. 添加一个TemplateColumn列来显示数据的条数。
3. 在GridView的footer添加一个搜索功能。
4. 当点击那个搜索按钮时触发一个事件。
代码部分:
1. GridView的扩展类:
view plaincopy to clipboardprint?
public class SearchGridView : GridView
public class SearchGridView : GridView
2. 创建一个模板列来显示每行记录的序列号。
view plaincopy to clipboardprint?
public class NumberColumn : ITemplate
{
public void InstantiateIn(Control container)
{
}
}
public class NumberColumn : ITemplate
{
public void InstantiateIn(Control container)
{
}
}
3. 在SearchableGrivView中我重载了OnInite方法来添加序列号的列为GridView的第一列。这里有个标志位ShowRowNumber如果是true的话才显示序列号列。
view plaincopy to clipboardprint?
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//If showrownumber option is turned on then add
//the template column as the first column.
if (!IsDesign() && ShowRowNumber)
{
TemplateField tmpCol = new TemplateField();
NumberColumn numCol = new NumberColumn();
tmpCol.ItemTemplate = numCol;
// Insert this as the first column
this.Columns.Insert(0, tmpCol);
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//If showrownumber option is turned on then add
//the template column as the first column.
if (!IsDesign() && ShowRowNumber)
{
TemplateField tmpCol = new TemplateField();
NumberColumn numCol = new NumberColumn();
tmpCol.ItemTemplate = numCol;
// Insert this as the first column
this.Columns.Insert(0, tmpCol);
}
}
4. 方法OnRowCreated在每一行被创建的时候会被调用。通过判断当前行的RowType可以在Footer中添加总的行数和搜索模块。
view plaincopy to clipboardprint?
protected override void OnRowCreated(GridViewRowEventArgs e)
{
base.OnRowCreated(e);
if (!IsDesign()) //During Runtime
{
if (e.Row.RowType == DataControlRowType.Footer)
{
//If ShowFooter is set to true
if (ShowFooter && e.Row.Cells.Count > 0)
{
//If TotalRows has to be shown
if (ShowTotalRows)
{
e.Row.Cells[0].Text = ViewState[NO_OF_ROWS] + " Rows.";
}
if (e.Row.Cells[e.Row.Cells.Count - 1].Controls.Count == 0)
{
//Create the search control
Table table = new Table();
table.Style.Add("width", "100%");
table.Style.Add("align", "right");
TableRow tr = new TableRow();
TableCell tc = new TableCell();
tc.Style.Add("align", "right");
tc.Style.Add("width", "100%");
//Populate the dropdownlist with the Ids
//of the columns to be filtered
if (_ddlFinder.Items.Count == 0)
SetFilter();
_btnSearch.Width = 20;
_btnSearch.Height = 20;
_btnSearch.ImageAlign = ImageAlign.AbsMiddle;