Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>OK hope you haven't solved this yet because I took a few minutes to come up with an example that I think will do pretty much what you want.</p> <p>DB access uses a stored procedure but you can use a ObjectDataSource with DAL, or just inline the SQL statement on the SqlDataSource, etc.</p> <p>Markup:</p> <pre><code>Product ID: &lt;asp:TextBox ID="TextBox1" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;asp:CompareValidator ID="CompareValidator1" ControlToValidate="TextBox1" runat="server" ErrorMessage="You must enter a number" ValidationGroup="vg1" Type="Integer" Operator="DataTypeCheck"&gt;&lt;/asp:CompareValidator&gt; &lt;br /&gt; Description: &lt;asp:TextBox ID="TextBox2" runat="server"&gt;&lt;/asp:TextBox&gt;&lt;br /&gt; &lt;asp:Button ID="cmdSearch" runat="server" Text="Search" ValidationGroup="vg1" /&gt;&lt;br /&gt; &lt;asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"&gt; &lt;/asp:GridView&gt; &lt;asp:SqlDataSource ID="SqlDataSource1" runat="server" SelectCommand="spGetProducts" CancelSelectOnNullParameter="False" SelectCommandType="StoredProcedure"&gt; &lt;SelectParameters&gt; &lt;asp:ControlParameter ControlID="TextBox1" PropertyName="Text" DbType="String" DefaultValue="" /&gt; &lt;asp:ControlParameter ControlID="TextBox2" PropertyName="Text" DbType="Int32" DefaultValue="" /&gt; &lt;/SelectParameters&gt; &lt;/asp:SqlDataSource&gt; </code></pre> <p>And T-SQL for your query:</p> <pre><code>CREATE PROCEDURE spGetProducts @ProductId int = NULL ,@ProductDescription nvarchar(100) = NULL AS BEGIN SELECT [ProductId] ,[ProductDescription] FROM [Products] WHERE ( ( (@ProductId IS NULL) OR ([ProductId] LIKE % + @ProductId + %) ) AND ( (@ProductDescription IS NULL) OR ([ProductDescription] LIKE % + @ProductDescription + %;) ) ); END </code></pre> <p>If the user doesn't enter anything in either of the fields, the SqlDataSource will still bind due to <code>SqlDataSource.CancelSelectOnNullParameter = False</code> but the empty parameter will not be sent with the query due to <code>ControlParameter.DefaultValue</code> being set. The stored procedure will then insert the NULL value into the parameter and basically skip that part of the filtering in the WHERE clause.</p> <p>Hope this helps.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload