Pass an optional parameter to a Web Forms SqlDataSource
SqlDataSource can cancel selection when a select parameter is null. Set CancelSelectOnNullParameter="false" only when the procedure deliberately accepts SQL NULL.
For a stored procedure, the direct SqlDataSource path is usually clearer than intercepting a LinqDataSource selection. This article applies to an existing .NET Framework Web Forms application.
Create a small demonstration procedure
Use a disposable SQL Server test database where dbo.FindExample does not exist. This creation must fail rather than replace an existing procedure:
CREATE PROCEDURE dbo.FindExample @Name nvarchar(50) = NULL
AS
BEGIN
SET NOCOUNT ON;
SELECT 7 AS Id, N'Example' AS Name
WHERE @Name IS NULL OR @Name = N'Example';
END;
Configure a Demo connection string for the application, then put this markup inside a Web Forms server form:
<asp:TextBox ID="Search" runat="server" />
<asp:Button ID="SearchButton" runat="server" Text="Search" />
<asp:SqlDataSource ID="Data" runat="server"
ConnectionString="<%$ ConnectionStrings:Demo %>"
SelectCommand="dbo.FindExample" SelectCommandType="StoredProcedure"
CancelSelectOnNullParameter="false">
<SelectParameters>
<asp:ControlParameter Name="Name" ControlID="Search" PropertyName="Text"
Type="String" ConvertEmptyStringToNull="true" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="Items" runat="server" DataSourceID="Data" />
With Search empty, the row appears. Enter Missing and click Search. No row matches.
Preserve the parameter contract
SQL NULL and an omitted parameter are different. A procedure's default applies when an argument is omitted, while this control sends NULL. Do not disable null cancellation to work around a missing required key or access-control parameter. Validate required input and fix its binding instead.
If retaining a LinqDataSource.Selecting handler, materialize its result while its context is alive and assign that result to e.Result. Avoid returning a deferred query from a context that has already been disposed.
Official references

Author: Herman Schoenfeld