views:

314

answers:

5

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.

+2  A: 

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;
 }
Mendy
The latter does not need the extra `if(...) return 0;`.Also, any method taking an `out` parameter must assign a value to it before it returns.So `val` will always be initialized, there is no need to do it again. ( the `=0` part.)
andras
@andras: Thanks for the notes.
Mendy
You're welcome.
andras
+3  A: 

What about, um, accepting an integer in your function that should read integers, and use int.Parse or int.TryParse on the string beforehand?

zneak
A: 

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.

Fadrian Sudaman
That's a great idea, although is too much work for such a simple thing.
diamandiev
Or a masked textbox already limits the input values
benPearce
Seriously, overkill. You can attach a validator to a "normal" textbox much easier than making your own subclass and trying to use that.
Coderer
Like I said just another perspective. For one used, it is overkill but if the same behaviour is expected everywhere in the application the abstraction and encapsulation will be beneficial
Fadrian Sudaman
A: 

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.

Michael Fitzpatrick
A: 

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.

Coderer