Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

you can set the default value to null in your stored procedure so in case the textbox is empty you simply do not have to pass anything, to do so just write = NULL after the parameter type in the stored procedure parameters list.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top