Convert String.Empty to Nothing/Null
Is there a .Net function that does that. I guess if there isn't i have to make my own method.
The thing is i have a function. It accepts integers. If you pass a 0 integer or a null value it still works. Problem is that the value of an empty textbox is a String.Empty value.
I don't want to use if's. I mean it could but its much nicer if i can just 开发者_运维百科call my function like this
MyFunction(txtTextbox.Text)
But it won't work because it can't convert the string.empty to a integer.
I guess you need:
if(string.IsNullOrEmpty(value)) value = null;
or
int MyFunction(string value) { if(string.IsNullOrEmpty(value)) return 0; int val = 0; int.TryParse(value, out val); return val; }
What about, um, accepting an integer in your function that should read integers, and use int.Parse
or int.TryParse
on the string beforehand?
Just from a different perspective, I assume that your textbox will also need to allow only numeric to be entered. Otherwise just handling null isnt going to be bullet proof against someone entering non numeric. There must either be some maskings, event handler or validation you have created for it. How about create your own NumTextBox that inherit from TextBox with the input restriction behaviours that you already had and either override Text property or create a new property calls Value which looks after all the conversions and return the appropriate value consistently through out your system.
try this
Sub MyFunction(ByVal Param1Integer as Integer)
' Do Something
End Sub
Sub MyFunction(ByVal Param1String as String)
MyFunction(Val(Param1String))
End Sub
It assumes that an empty string is the same as 0.
Have you looked into using a NumericUpDown (spin control)? It has a .Value member (always a valid Integer!) instead of having to convert from a String. You can limit the upper and lower values, as well as set a default.
I would just use an inline IF statement (VB):
MyFunction(IIf(txtTextBox.Text Is Nothing, "", txtTextBox.Text))
精彩评论