请参考此链接在 ASP.Net GridView 中搜索而不刷新页面。
[ASP.NET GridView 搜索不刷新整个页面]
http://www.ashishblog.com/search-sort-in-gridview-using-c-net-ajax-and-jquery/
这是我的 aspx 页面,在 AJAX 更新面板中具有搜索文本框和网格视图。
<asp:ScriptManager ID="ScriptManager" runat="server" />
Search: <asp:TextBox ID="txtSearch" runat="server" OnTextChanged="txtSearch_TextChanged" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<div class="GridviewDiv">
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
AllowSorting="true" DataSourceID="dsGridview" Width="540px" PageSize="10" CssClass="yui">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" SortExpression="id" ItemStyle-Width="40px"
ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
<ItemStyle Width="120px" HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lblFirstname" Text='<%# HighlightText(Eval("FirstName").ToString()) %>' runat="server"
CssClass="TextField" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
<ItemStyle Width="120px" HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lblLastname" Text='<%# HighlightText(Eval("LastName").ToString()) %>' runat="server"
CssClass="TextField" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department"
ItemStyle-Width="130px" />
<asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location"
ItemStyle-Width="130px" />
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtSearch" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
--> 这是我在页面加载事件中添加文件的代码。
string SearchString = "";
protected void Page_Load(object sender, EventArgs e)
{
txtSearch.Attributes.Add("onkeyup", "setTimeout('__doPostBack(\\'" + txtSearch.ClientID.Replace("_", "$") + "\\',\\'\\')', 0);");
if (!IsPostBack)
{
Gridview1.DataBind();
}
}
protected void txtSearch_TextChanged(object sender, EventArgs e)
{
SearchString = txtSearch.Text;
}
public string HighlightText(string InputTxt)
{
string Search_Str = txtSearch.Text.ToString();
// Setup the regular expression and add the Or operator.
Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
// Highlight keywords by calling the
//delegate each time a keyword is found.
return RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));
// Set the RegExp to null.
RegExp = null;
}
public string ReplaceKeyWords(Match m)
{
return "<span class=highlight>" + m.Value + "</span>";
}