SqlDataSource 数据过滤的问题
我想通过多个文本框中的值对gridview进行过滤,即和它相关的sqldatasource能得到多个控件参数以在filterExpression中写筛选的sql语句
先看一下我做的多种尝试,我填写的是能在数据库中‘查得到值的’
尝试一:
<form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Button" /> <asp:GridView ID="GridView1" runat="server" AllowPaging="true" PageSize="5" DataSourceID="SqlDataSource1"> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=pdcx;User ID=pdcx;Password=pdcx;Unicode=True" ProviderName="System.Data.OracleClient" SelectCommand="SELECT * from US_USER" FilterExpression="us003='{0}'"> <FilterParameters> <asp:ControlParameter Name="code" ControlID="TextBox1" /> </FilterParameters> </asp:SqlDataSource> </div> </form>
<form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Button" /> <asp:GridView ID="GridView1" runat="server" AllowPaging="true" PageSize="5" DataSourceID="SqlDataSource1"> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=pdcx;User ID=pdcx;Password=pdcx;Unicode=True" ProviderName="System.Data.OracleClient" SelectCommand="SELECT * from US_USER" FilterExpression="us003='{0}' or us004='{1}'"> <FilterParameters> <asp:ControlParameter Name="code" ControlID="TextBox1" /> <asp:ControlParameter Name="t" ControlID="TextBox2" /> </FilterParameters> </asp:SqlDataSource> </div> </form>
<asp:ControlParameter Name="code" ControlID="TextBox1" ConvertEmptyStringToNull="false" /> <asp:ControlParameter Name="t" ConvertEmptyStringToNull="false" ControlID="TextBox2" />
[解决办法]
如果要实现楼主想要得的or逻辑,可能就需要用代码来控制了,例如:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:HSDBConnectionString %>"
SelectCommand="SELECT * FROM [TABLE1]" FilterExpression="field1 = '{0}' or field2 = '{1}'" OnFiltering="SqlDataSource1_Filtering">
<FilterParameters>
<asp:ControlParameter ControlID="TextBox1" Name="field1" PropertyName="Text" DefaultValue="" />
<asp:ControlParameter ControlID="TextBox2" Name="field2" PropertyName="Text" DefaultValue="" />
</FilterParameters>
</asp:SqlDataSource>
*****************************************************
protected void SqlDataSource1_Filtering(object sender, SqlDataSourceFilteringEventArgs e)
{
if (e.ParameterValues[0] == null && e.ParameterValues[1] != null)
e.ParameterValues[0] = "不可能出现的值";
if (e.ParameterValues[0] != null && e.ParameterValues[1] == null)
e.ParameterValues[1] = "不可能出现的值";
}