如何使用转发器实现搜索功能?

时间:2012-08-20 13:19:07

标签: asp.net webforms

我有一个像这样的aspx页面:

<asp:TextBox ID="SearchInput" AutoPostBack="true" runat="server" />
<asp:Repeater ID="SelectUserListItemRepeater" runat="server">
    <ItemTemplate>
        <div><%# DataBinder.Eval(Container.DataItem, "Title")%></div>
    </ItemTemplate>
</asp:Repeater>

这样的代码背后。

using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test : UserControl
{
    private IList<TestItem> items;

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        items = new List<TestItem>();
        items.Add(new TestItem { Title="Lars"});
        items.Add(new TestItem { Title = "Johan" });
        items.Add(new TestItem { Title = "Bob" });
        SelectUserListItemRepeater.DataSource = items;
        SelectUserListItemRepeater.DataBind();

        SearchInput.TextChanged += new EventHandler(SearchInput_TextChanged);
    }

    void SearchInput_TextChanged(object sender, EventArgs e)
    {
        var input = sender as TextBox;
        var searchResult = items.Where(i => i.Title.Contains(input.Text));
        /* Here I would like to show this search result in the Repeater, 
         * but what is the best way to do it?
         */ 
    }
}

public class TestItem {
    public string Title { get; set; }
}

在这种情况下实现搜索功能的最佳方法是什么?我有一个搜索文本输入和一个转发器,它在DIV元素中呈现字符串列表。当用户在输入中写入一些搜索键时,转发器应该只显示包含搜索关键字的字符串?如何隐藏不包含搜索键的其他RepeaterItem?或者我应该删除那些RepeaterItems如何?

2 个答案:

答案 0 :(得分:0)

试试这个:

 void SearchInput_TextChanged(object sender, EventArgs e)
    {
        var input = sender as TextBox;
        var searchResult = items.Where(i => i.Title.Contains(input.Text));
        SelectUserListItemRepeater.DataSource = searchResult;
        SelectUserListItemRepeater.DataBind();

    }

答案 1 :(得分:0)

试试这个

private static List<TestItem> items = new List<TestItem>();

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    items = new List<TestItem>();
    items.Add(new TestItem { Title="Lars"});
    items.Add(new TestItem { Title = "Johan" });
    items.Add(new TestItem { Title = "Bob" });

    SearchInput.TextChanged += new EventHandler(SearchInput_TextChanged);

    // bind repeater.
    BindRepeater();

}

protected void SearchInput_TextChanged(object sender, EventArgs e)
{
    var input = sender as TextBox;
    items = items.Where(i => i.Title.Contains(input.Text)).ToList();
    BindRepeater();
}

private void BindRepeater()
{
    SelectUserListItemRepeater.DataSource = items;
    SelectUserListItemRepeater.DataBind();
}