开发者

ASP.Net Textbox control doesn't return NULL when it is empty

In reference to this question that I just asked -- SQL - Select all when filter value is empty -- it appears that for some reason, an empty TextBox'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;


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;
    }
}


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>


"""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


Set the default parameter value in the ASP code to null.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜