In reference to this question that I just asked, http://stackoverflow.com/questions/2451579/sql-select-all-when-filter-value-is-empty, it appears that for some reason, an empty text box's value is not being fed to SQL Server as NULL, as it ought to be. Any ideas on how to fix this?
An empty text box will contain string.Empty
, not null
.
From the TextBox.Text documentation:
Property Value
Type: System.String
The text displayed in the TextBox control. The default is an empty string ("").
If you want to make sure it goes to the database as null
, then convert it on the way in:
string value = !string.IsNullOrEmpty(tb.Text) ? tb.Text: null;
You can do this without any C#.
Simply set the parameters ConvertEmptyStringToNull property to true, eg:
<asp:ObjectDataSource runat="server" ID="ObjectDataSourceExample" TypeName="Example.ExampleTableAdapter" SelectMethod="GetDataBySomething">
<SelectParameters>
<asp:ControlParameter Name="Something" ConvertEmptyStringToNull="true" ControlID="tbSomething" />
</SelectParameters>
</asp:ObjectDataSource>
just to enlighten you :)
this is from reflector:
public virtual string Text
{
get
{
string str = (string) this.ViewState["Text"];
if (str != null)
{
return str;
}
return string.Empty;
}
set
{
this.ViewState["Text"] = value;
}
}
I think it's better don't insert empty value into database, if the textbox is empty.
"""Property Value Type: System.String The text displayed in the TextBox control. The default is an empty string ("")."""
Aaronaught is correct.
Null is a very loosely used term and shouldn't be, and can easily be confused with 'Nothing' which is far better to use in programming. A textbox.text value will never be null, it will be "". Nothing refers to whether you have initialized the string variable or not. sooooo
the textbox itself could = Nothing the textbox.text can only equal "" (or string.empty - function does the same thing) if the textbox isnot nothing
It's a general good rule of thumb to use string.empty or "" when referring to whether a string contains any characters
Obviously the Paramater you use in ur sqlcommand needs to be null or not so...
In VB:
If TextBox.Text = "" Then VariableUsedInSqlCommand = Nothing End If From her you can set the default paramater value in SP or Inline SqlCommand to be Null, so when it recieves a paramter that Is Nothing, it reverts the paramater to = Null
In Stored Procedure (if you're sending the textbox.text value directly to a SP Paramater):
If (@Paramater = "") Begin
end else begin
end