ASP.NET GridView中使用搜索框(SearchableGridView)

 

介绍:

我正在搜寻一种方法实现在ASP.NET GridView控件包含搜索框。我找不到一个完美的解决方案,决定自己去实现它。这里所以写出我的解决方案。

为什么使用这种方案?

您可以使用此种方案和实施行的表格过滤变得非常容易。搜索和过滤操作可以由公正处理的搜索事件引发。此外,该GridView还可以设置选项以显示行序列号,行的总数,并显示页眉和页脚即使没有行在GridView可用。(默认情况下,页眉和页脚是隐藏,GridView没有数据行。)

该解决方案

我做了什么

1.我扩展GridView和创建了一个SearchableGridView类。
2.
添加了一个TemplateColumn显示行数。

3. 在页脚,添加了控件来处理搜查事件。
4.
当开启搜索的时候,,传递搜索字符串给触发的事件。

代码:

1、通过创建了一个SearchableGridView来扩展GridView,实现在Gridview的页脚有一个搜索框.

 

public   class  NumberColumn : ITemplate
{
    
public   void  InstantiateIn(Control container)
    {
    }
}

 

SearchableGridView类中,我重写的OnInit函数添加模板的第一列显示的行序号,如果ShowRowNumber标记将被打开。

 

Code
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);
    }
}

 

当每一行创建时,OnRowCreated方法被执行。在此期间时,对创建的行类型的不同,在表尾,我们添加搜索控件和显示行数量label,在表身,添加行数,在表头,该添加列标题。

 

 

Code
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;
                    _btnSearch.AlternateText 
= "Search";
                    
//Assign the function that is called when search button is clicked
                    _btnSearch.Click += new ImageClickEventHandler(_btnSearch_Click);
                    
                    tc.Controls.Add(_ddlFinder);
                    tc.Controls.Add(_tbSearch);
                    tc.Controls.Add(_btnSearch);
                    tr.Cells.Add(tc);
                    table.Rows.Add(tr);
                    _pnlSearchFooter.Controls.Add(table);
                    e.Row.Cells[e.Row.Cells.Count 
- 1].Controls.Add(_pnlSearchFooter);
                
                }
            }
        }
        
if (e.Row.RowType == DataControlRowType.Header)
        {
            
// If ShowHeader is set to true and 
            
// If Row number has to be shown
            if (ShowRowNumber && ShowHeader) 
            {
                e.Row.Cells[
0].Text = "Sno";
            }
        }
        
else if (e.Row.RowType == DataControlRowType.DataRow)
        {
            
if (ShowRowNumber)
            {
                
//Set the row number in every row
                e.Row.Cells[0].Text = (e.Row.RowIndex + 
                  (
this.PageSize * this.PageIndex) + 1).ToString();
            }
        }
    }
}

 

SearchableGridViewSearchFilters属性设置的搜索选项的下拉列表的值。它的Text属性对应的显示名称在DropDownList和列表项的值属性是数据源的列名。

 

public   void  SetFilter()
{
    _ddlFinder.Items.Clear();
    
// Copy the items to the dropdownlist
     foreach  (ListItem li  in  SearchFilters)
        _ddlFinder.Items.Add(li);
}

 

现在,让我们进入到搜索的事件处理。为此,我创建了一个委托和事件SearchGrid,搜索按钮时被击中。搜索字符串形成使用语法_ddlFinder.SelectedValue + " like '" + _tbSearch.Text.Trim() + "%'".

 

 

Code
public delegate void SearchGridEventHandler(string _strSearch);
public event SearchGridEventHandler SearchGrid;
void _btnSearch_Click(object sender, ImageClickEventArgs e)
{
    
string sSearchText = ConstructSearchString();
    OnSearchGrid(sSearchText);
}
protected string ConstructSearchString()
{
    
string _strText = _tbSearch.Text.Trim();
    
if (_strText == string.Empty)
        
return string.Empty;
    
return _ddlFinder.SelectedValue + " like '" + _strText + "%'";
}
protected void OnSearchGrid(string _strSearch)
{
    
if (SearchGrid != null)
    {
        SearchGrid(_strSearch);
    }
}

 

显示页脚时,当没有返回任何行
GridView的默认属性是隐藏的页眉和页脚时没有行被绑定到它。设置一个空项目模板只可以显示模板而不是页眉或页脚。在我们的情况,页脚,必须始终显示,不论绑定到SearchableGridView行数,因为搜索选项应该是可见的。要做到这一点,我不得不重写CreateChildControls方法如下:

 

Code
protected override int CreateChildControls(System.Collections.IEnumerable dataSource, 
                                           
bool dataBinding)
{
    
int count = base.CreateChildControls(dataSource, dataBinding);
    
//  no rows in grid. create header and footer in this case
    if (count == 0 && (ShowEmptyFooter || ShowEmptyHeader))
    {
        
//  create the table
        Table table = this.CreateChildTable();
        DataControlField[] fields;
        
if (this.AutoGenerateColumns)
        {
            PagedDataSource source 
= new PagedDataSource();
            source.DataSource 
= dataSource;
            System.Collections.ICollection autoGeneratedColumns 
= 
                                           
this.CreateColumns(source, true);
            fields 
= new DataControlField[autoGeneratedColumns.Count];
            autoGeneratedColumns.CopyTo(fields, 
0);
        }
        
else
        {
            fields 
= new DataControlField[this.Columns.Count];
            
this.Columns.CopyTo(fields, 0);
        }
        
if (ShowEmptyHeader)
        {
            
//  create a new header row
            GridViewRow headerRow = base.CreateRow(-1-1, DataControlRowType.Header, 
                                                   DataControlRowState.Normal);
            
this.InitializeRow(headerRow, fields);
            
// Fire the OnRowCreated event to handle showing row numbers
            OnRowCreated(new GridViewRowEventArgs(headerRow));
            
//  add the header row to the table
            table.Rows.Add(headerRow);
        }
        
//  create the empty row
        GridViewRow emptyRow = new GridViewRow(-1-1, DataControlRowType.EmptyDataRow, 
                                               DataControlRowState.Normal);
        TableCell cell 
= new TableCell();
        cell.ColumnSpan 
= fields.Length;
        cell.Width 
= Unit.Percentage(100);
        
//  respect the precedence order if both EmptyDataTemplate
        
//  and EmptyDataText are both supplied 
        if (this.EmptyDataTemplate != null)
        {
            
this.EmptyDataTemplate.InstantiateIn(cell);
        }
        
else if (!string.IsNullOrEmpty(this.EmptyDataText))
        {
            cell.Controls.Add(
new LiteralControl(EmptyDataText));
        }
        emptyRow.Cells.Add(cell);
        table.Rows.Add(emptyRow);
        
if (ShowEmptyFooter)
        {
            
//  create footer row
            GridViewRow footerRow = base.CreateRow(-1-1, DataControlRowType.Footer, 
                                                   DataControlRowState.Normal);
            
this.InitializeRow(footerRow, fields);
            
// Fire the OnRowCreated event to handle showing
            
// search tool and total number of rows
            OnRowCreated(new GridViewRowEventArgs(footerRow));
            
//  add the footer to the table
            table.Rows.Add(footerRow);
        }
        
this.Controls.Clear();
        
this.Controls.Add(table);
    }
    
return count;
}

 

例子:
让我用一个例子帮助说明上面的控件。为此,我使用Northwind数据库中的客户表。

步骤1:创建与选择查询数据源dsCustomersSELECT CustomerID, CompanyName, Address, City, Country FROM Customers

步骤2:创建一个SearchableGridView实例和设置SearchFilters属性有关于的搜索选择项。

 

步骤3:添加两个隐藏字段hfSearchTexthfSort分别存储搜索文本和文本的排序。

4步:用SearchGrid事件来设置SearchableGridView数据源和过滤的搜索字符串。 hfSearchTexthfSort是隐藏的领域持有的搜索字符串和SearchableGridView排序字符串。BindData方法实现绑定的过滤和排序后的数据。

 

Code
protected void SearchGridView1_SearchGrid(string _strSearch)
{
    hfSearchText.Value 
= _strSearch;
    BindData();
}
protected void SearchGridView1_Sorting(object sender, GridViewSortEventArgs e)
{
    
//If hfSort has the same value as before, 
    
//the sorting should be done in descending order
    if (hfSort.Value == e.SortExpression)
        hfSort.Value 
= e.SortExpression + " Desc";
    
else
        hfSort.Value 
= e.SortExpression;
    BindData();
}
void BindData()
{
    
//hfSearchText has the search string returned from the grid.
    if (hfSearchText.Value != "")
        dsCustomers.SelectCommand 
+= " where " + hfSearchText.Value;
    DataView dv 
= (DataView)dsCustomers.Select(new DataSourceSelectArguments());
    
//hfSort has the sort string returned from the grid.
    if (hfSort.Value != "")
        dv.Sort 
= hfSort.Value;
    SearchGridView1.DataSource 
= dv;
    
try
    {
        SearchGridView1.DataBind();
    }
    
catch (Exception exp)
    {
        
//If databinding threw exception b’coz current 
        
//page index is > than available page index
        SearchGridView1.PageIndex = 0;
        SearchGridView1.DataBind();
    }
    
finally
    {
        
//Select the first row returned
        if (SearchGridView1.Rows.Count > 0)
            SearchGridView1.SelectedIndex 
= 0;
    }
}

 

结论
SearchableGridView
将是非常有用,当有一个表格中的数据行很大的时候。通过执行搜索没有太多麻烦。

翻译:http://www.codeproject.com/KB/webforms/SearchSortableGridView.aspx

代码:http://www.codeproject.com/KB/webforms/SearchSortableGridView.aspx

小弟第一次翻译文章,错误多多,请多多指出!

 

 



(全文完)


以下为广告部分

您部署的HTTPS网站安全吗?

如果您想看下您的网站HTTPS部署的是否安全,花1分钟时间来 myssl.com 检测以下吧。让您的HTTPS网站变得更安全!

SSL检测评估

快速了解HTTPS网站安全情况。

安全评级(A+、A、A-...)、行业合规检测、证书信息查看、证书链信息以及补完、服务器套件信息、证书兼容性检测等。

SSL证书工具

安装部署SSL证书变得更方便。

SSL证书内容查看、SSL证书格式转换、CSR在线生成、SSL私钥加解密、CAA检测等。

SSL漏洞检测

让服务器远离SSL证书漏洞侵扰

TLS ROBOT漏洞检测、心血漏洞检测、FREAK Attack漏洞检测、SSL Poodle漏洞检测、CCS注入漏洞检测。

转载于:https://www.cnblogs.com/zhuqil/archive/2009/11/18/1605672.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据您的描述,您需要在良品和不良品测试结束后,解除对条码的限制,使得无论输入什么条码,都可以发送到ICT测试软件并提示“已点检,请进行ICT测试”,而且label状态栏始终是黄色。那么您可以参考下面的代码进行修改: ``` if (e.KeyCode == Keys.Enter) { // 判断条码是否为设置的良品或不良品条码 string barcode = txt_barcode.Text.Trim(); string connectionString = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = db.accdb;Jet OLEDB:Database Password = @maruhi"; using (OleDbConnection connection = new OleDbConnection(connectionString)) { connection.Open(); OleDbCommand command = new OleDbCommand("SELECT COUNT(*) FROM ICT_test WHERE Date=@date AND Barcode=@barcode AND Result='OK'", connection); command.Parameters.AddWithValue("@date", DateTime.Now.ToString("yyyy-MM-dd")); command.Parameters.AddWithValue("@barcode", barcode); int count = (int)command.ExecuteScalar(); if (count == 0) { // 条码错误 lb_test_state.BackColor = Color.Red; lb_test_state.Text = "条码错误 "; // 良品或不良品点检 if (goodBarcodeList.Contains(barcode)) { lb_test_state.BackColor = Color.Yellow; lb_test_state.Text = "请进行良品点检"; SendBarcode(); } else if (badBarcodeList.Contains(barcode)) { lb_test_state.BackColor = Color.Yellow; lb_test_state.Text = "请进行不良品点检"; SendBarcode(); } else { lb_test_state.BackColor = Color.Yellow; lb_test_state.Text = "已点检,请进行ICT测试"; SendBarcode(); } } else { lb_test_state.BackColor = Color.Green; lb_test_state.Text = "测试通过"; SendBarcode(); } } } ``` 在代码,我们加入了一个`else`语句,当条码不是良品和不良品条码时,就会执行这个`else`语句,将label状态栏设为黄色,并提示“已点检,请进行ICT测试”,然后将条码发送到ICT测试软件。这样,无论输入什么条码,都可以发送到ICT测试软件并提示“已点检,请进行ICT测试”,而且label状态栏始终是黄色。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值