我有一个gridview,我通过代码绑定绑定,我想根据用户在文本框中给出的值过滤gridview.
如果我能够在没有任何回发的情况下过滤gridview,那就太棒了.
请帮忙!
提前致谢
你可以运行一个过滤表达式
<asp:sqldatasource id="articles" runat="server"
connectionstring="<%$ ConnectionStrings:aspa %>"
selectcommand="SELECT title, url, added, updated FROM aspx_articles ORDER BY title"
filterexpression="title LIKE '%{0}%' or url LIKE '%{0}%'">
<filterparameters>
<asp:controlparameter controlid="searchBox" propertyname="Text" />
</filterparameters>
</asp:sqldatasource>
Run Code Online (Sandbox Code Playgroud)
或者这样
你是否在GridView外部有一个TextBox,当你输入数据并按下按钮时,GirdView应该过滤掉那些数据?
如果是这样,请确保您的select命令可以使用您要过滤的值来获取参数.将ControlParameter添加到DataSource控件的SelectParameters colelction(如果使用DataSource控件).
下面是一个使用Northwind数据库的示例,这可能对您有所帮助:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
DataKeyNames="ProductID" DataSourceID="SqlDataSource1" ShowFooter="True">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [UnitsInStock], [UnitPrice] FROM [Alphabetical list of products] WHERE ([ProductName] LIKE '%' + @ProductName + '%')">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox1" DefaultValue="%" Name="ProductName" PropertyName="Text"
Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Run Code Online (Sandbox Code Playgroud)
代码见http://forums.asp.net/p/1034014/2904713.aspx