I get the exception "Input string was not in correct format". I want to handle that exception and add my own error. The input should be an int. Where should I do this? I have an objectdatasource with listview and I'm having trouble getting the textbox.text from the code behind so I can use tryParse.
-
This is not validation. If the value is wrong, it should never be set like you have in your code.leppie– leppie2012-04-02 11:39:51 +00:00Commented Apr 2, 2012 at 11:39
-
5this property already accepts INT. What do you mean, by "validation".?Tigran– Tigran2012-04-02 11:40:21 +00:00Commented Apr 2, 2012 at 11:40
-
And what do you think it can be? Other than intJleruOHeP– JleruOHeP2012-04-02 11:40:45 +00:00Commented Apr 2, 2012 at 11:40
-
@leppie: This is perfectly good ViewModel code.Daniel Hilgarth– Daniel Hilgarth2012-04-02 11:41:18 +00:00Commented Apr 2, 2012 at 11:41
-
Int32.TryParse(...) ?? msdn.microsoft.com/en-us/library/system.int32.tryparse.aspxBridge– Bridge2012-04-02 11:41:52 +00:00Commented Apr 2, 2012 at 11:41
3 Answers
Your property is of type Int32. You cannot assign anything else than a valid integer to this property. Now if you have some user input which is under the form of a string and then you need to assign it to the integer property you could use the int.TryParse method to ensure that the value entered by the user is a valid integer.
For example:
string someValueEnteredByUser = ...
int value;
if (!int.TryParse(someValueEnteredByUser, out value))
{
// the value entered by the user is not a valid integer
}
else
{
// the value is a valid integer => you can use the value variable here
}
1 Comment
'value' will always be of the same type as your variable. Thus having this:
private bool mabool = false;
public bool MaBool
{
get { return mabool; }
set { mabool = value; }
}
Won't ever crash. This because, as I said, value will be the same type of the variable. In this case, value is a boolean.
Try it with a class:
public class Rotator
{
public Roll, Pitch, Yaw;
// Declarations here (...)
}
private Rotator rotation = new Rotator();
public Rotator Rotation
{
get { return rotation; }
set
{
// Since value is of the same type as our variable (Rotator)
// then we can access it's components.
if (value.Yaw > 180) // Limit yaw to a maximum of 180°
value.Yaw = 180;
else if (value.Yaw < -180) // Limit yaw to a minimum of -180°
value.Yaw = -180;
rotation = value;
}
}
As seen on the second example, value is a Rotator, thus we can access it's components.