ASP.NET GridView 分页本身不直接支持搜索,但您可以通过以下方法实现搜索功能:
在 GridView 的 DataSource 中添加一个自定义属性,例如 SearchText,用于存储用户输入的搜索关键字。
在 GridView 的 RowCreated 事件中,检查每一行的数据是否包含搜索关键字。如果包含,则将该行设置为不可选。
为 GridView 添加一个搜索框,用于输入搜索关键字。当用户输入关键字时,更新 DataSource 中的 SearchText 属性,并重新绑定数据。
以下是一个简单的示例:
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" OnRowCreated="GridView1_RowCreated"> </asp:GridView> protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindGridView(); } } private void BindGridView() { string searchText = txtSearch.Text; DataTable dt = GetData(searchText); GridView1.DataSource = dt; GridView1.DataBind(); } private DataTable GetData(string searchText) { // 在这里添加您的数据获取逻辑,例如从数据库中查询数据 // 将搜索关键字添加到查询条件中 string query = "SELECT * FROM YourTable WHERE YourColumn LIKE '%" + searchText + "%'"; // 执行查询并返回结果 using (SqlConnection connection = new SqlConnection("YourConnectionString")) { using (SqlCommand command = new SqlCommand(query, connection)) { connection.Open(); using (SqlDataAdapter adapter = new SqlDataAdapter(command)) { DataTable dt = new DataTable(); adapter.Fill(dt); return dt; } } } } protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { string searchText = txtSearch.Text; if (e.Row.DataItem.ToString().Contains(searchText)) { e.Row.Attributes["class"] += " disabled"; e.Row.Attributes["onclick"] = "return false;"; } } } 这样,当用户在搜索框中输入关键字时,GridView 会显示包含关键字的数据行,并将这些行设置为不可选。请注意,这个示例仅用于演示目的,您可能需要根据您的实际需求进行调整。