Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing blank field value to stored procedure ASP .NET C#

I want to return all rows from a SQL Server 2008 database table into a SQL data source if a textBox field is blank. So I made a stored procedure with an if @date IS NULL clause.

Although the stored procedure seems to be working fine in Visual Studio 2008 the actual webpage displays no results.

I am guessing I have to send a DBNull value to the stored proc if textBox.Text == string.Empty. I tried the SqlDataSource1.SelectParameters.Add but it seems that I get a conversion error from DBNull.Value to string.

Is this the source of my problems or am I missing something else? How would I pass DBNull.Value to a stored proc if a textfield is blank?

like image 452
user626873 Avatar asked Feb 21 '11 15:02

user626873


People also ask

Can we pass NULL value in stored procedure?

If you want you're stored procedure to accept nulls then you first need to specify this in your input variables.

How do you pass a null parameter to a stored procedure in SQL?

In the create procedure statement, you can declare null as the default value for individual parameters: create procedure procedure_name @param datatype [ = null ] [, @param datatype [ = null ]]... If the user does not supply a parameter, Adaptive Server executes the stored procedure without displaying an error message.

Can we pass parameters to stored procedures?

You can also pass parameters to a stored procedure, so that the stored procedure can act based on the parameter value(s) that is passed.


1 Answers

You need to ensure that CancelSelectOnNullParameter is set to false on your SqlDataSource, and that ConvertEmptyStringToNull is true on to needed parameter. It should look something like this in markup:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" CancelSelectOnNullParameter="false" SelectCommand="...">
  <SelectParameters>
    <asp:ControlParameter Name="..." ControlID="..." PropertyName="..." DbType="..." ConvertEmptyStringToNull="true"/>
    ...
  </SelectParameters>
</asp:SqlDataSource>

The problem will start if you have more then one Control that can provide null value and you want to allow only one of them to be null. In that case you must set CancelSelectOnNullParameter to true and use Selecting event to add DBNull.Value:

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
  if (String.IsNullOrEmpty(textBox.Text))
    ((IDbDataParameter)e.Command.Parameters["@name"]).Value = DBNull.Value;
}

That should allow you to solve your problems.

like image 114
tpeczek Avatar answered Sep 23 '22 18:09

tpeczek