C#Custom GridView

时间:2018-02-17 07:54:29

标签: c# asp.net caching search gridview

我对asp.net并不十分精通。我有一个基于asp的Web应用程序,我想创建一个自定义GridView,以便在我有一个搜索框时使用它并减少我的代码中的冗余。

我希望GridView位于我的textbox下方,并且文字更改GridView显示主要搜索结果和"更多"用于提前搜索的按钮,将打开一个新页面。任何人都可以帮助我如何开始?

感谢。

1 个答案:

答案 0 :(得分:1)

这是一个如何实现这一目标的小例子。首先添加搜索aspx页面所需的必要项目。请注意,这些按钮具有OnCommand,因此您可以随身携带CommandName

<asp:TextBox ID="SearchField" runat="server" MaxLength="50"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
    ErrorMessage="A search term is required" ValidationGroup="Search" 
    ControlToValidate="SearchField">
</asp:RequiredFieldValidator>

<asp:Button ID="SearchButton" runat="server" Text="Search" 
    OnCommand="DoSearch_Command" CommandName="Search" ValidationGroup="Search" />

<asp:GridView ID="SearchResultsGridView" runat="server" AutoGenerateColumns="true"></asp:GridView>

<asp:Button ID="MoreButton" runat="server" Text="More" 
    OnCommand="DoSearch_Command" CommandName="More"/>

现在,您在后面的代码中处理SearchMore的按钮点击。我使用List创建了一些虚拟数据,但您需要将其替换为包含搜索结果的正确数据源(List,DataTable等)。

protected void DoSearch_Command(object sender, CommandEventArgs e)
{
    //create a new item to hold search results, in this case a list
    List<string> searchResults = new List<string>();

    //the text from the textbox that contains the search word
    string searchTerm = SearchField.Text.Trim();

    //hide the 'more' button
    MoreButton.Visible = false;

    //add some dummy data for testing
    for (int i = 1; i <= 50; i++)
    {
        searchResults.Add("Search result " + i);
    }

    //if the results are more than 10 and the click is not from the 'more' button take 10 items
    if (searchResults.Count > 10 && e.CommandName == "Search")
    {
        searchResults = searchResults.Take(10).ToList();

        //show the more button
        MoreButton.Visible = true;
    }

    //show results in gridview
    SearchResultsGridView.DataSource = searchResults;
    SearchResultsGridView.DataBind();
}