Wednesday, June 4, 2014

How to pass NULL to SelectParameters in SQLDatasource?

Here is the problem
 
How to pass NULL to SelectParameters in SQLDatasource from .aspx or codebehind file?
 
.aspx Method

Two things:
1. First set the SqlDataSource Property CancelSelectOnNullParameter = false
2. Second set the parameter property ConvertEmptyStringToNull="true"
 
Example:

<asp:SqlDataSource ID="ds1" runat="server" ConnectionString='<%$ ConnectionStrings:dbConnString %> 'SelectCommand="someSelect @param1=@param1" CancelSelectOnNullParameter="false">

<SelectParameters>

<asp:Parameter Name="param1" Type="String"  ConvertEmptyStringToNull="true" />

</SelectParameters>

</asp:SqlDataSource>

-------------------------------------------------------------------------------------------------------------------

Codebehind Method

To pass from codebehind, the parameter need to be set in the proper event of Datasource.
Also no other properties of parameter need to set in aspx. Just declare a parameter.
In example below, I am passing null during "Select" call, so the code will look as:

Protected Sub SqlDataSource1_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles SqlDataSource1.Selecting
        If e.Command.Parameters("@param1").Value = "" Then
            e.Command.Parameters("@param1").Value = System.DBNull.Value
        End If    
End Sub


HTH
 

No comments: