我在网格视图中显示一些数据,一切正常。但是,我尝试在文本字段中添加搜索按钮,以便用户能够按名称(表格的第一列)过滤数据。因此,例如用户将输入" James"然后只显示名称为James的条目。 这是我的代码:
<asp:Button ID="Button1" runat="server" Text="Filter" OnClick="Button1_Click" />
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true"></asp:TextBox>
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataSourceID="ObjectDataSource1" >
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" SortExpression="Name" >
<HeaderStyle Width="450px" />
<ItemStyle HorizontalAlign="Center" Height="100px" Width="400px" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
</asp:BoundField>
<asp:BoundField DataField="Title" HeaderText="Title" ReadOnly="True" SortExpression="Title" >
<ItemStyle Width="400px" HorizontalAlign="Center" Height="100px" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
</asp:BoundField>
</Columns>
<HeaderStyle BackColor="#002d57" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#002756" HorizontalAlign="Left" />
<RowStyle ForeColor="#002756" />
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetData" TypeName="Test"></asp:ObjectDataSource>
在后面的代码中我尝试了类似的东西,但它仍然显示了表的所有结果,而不是我专门搜索的结果:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
((DataTable)GridView1.DataSource).DefaultView.RowFilter = "Name like '%" + textBox1.Text.Trim() + "%' ";
}
catch (Exception) { }
}
我有什么建议可以实现这个目标吗?
答案 0 :(得分:1)
你也可以这样做
DataView dv = ((DataTable)dataGridView1.DataSource).DefaultView;
dv.RowFilter = "Name LIKE '%" + textBox1.Text + "%'";
dataGridView1.DataSource = dv;
dv.DataBind();
答案 1 :(得分:0)
试试这个
((DataTable)GridView1.DataSource).DefaultView.RowFilter.Contains(textBox1.Text);
答案 2 :(得分:0)
//绑定gridview
时将DataTable保存在会话中// Session [&#34; Dt_GridView&#34;] = Your_datatable;
尝试以下代码
protected void Button1_Click(object sender, EventArgs e)
{
try
{
DataTable dt = (DataTable)Session["Dt_GridView"];
dt.DefaultView.RowFilter = "Name like '%" + textBox1.Text.Trim() + "%' ";
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex) { }
}
<强>更新强>
当您使用ObjectDataSource时,您可以直接调用FilterExpression方法,如下所示
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
ObjectDataSource1.FilterExpression = "Name LIKE '%" + TextBox1.Text + "%'";
}
}