开发者

C# Input string was not in a correct format

Working on parsing from a text box to int to get into the incrementHour method as shown.

if (txtHourPlus.Text != String.Empty)
            {
                time1.incrementHour(int.Parse(txtHour.Text));

            }

And in the time class: (the time1 objects class)

 public int incrementHour(int step)
        {
            if (step > 0 && hour < 24)
            {
                //step = step % hour;
                hour = (hour + step) % 24;
                time.AddHours(hour);
                return hour;
            }//end of if

            else
            {
                MessageBox.Show("Please enter a positive number.");

                return 0;
            }//end of else
        }//end of incrementHour

not sure why i'm getting this error. I'm converting it to the corrent data type. Because it accepts an int variable.


Alright w开发者_开发技巧ell i got it to take the value (small mistake >.> Don't even wanna say it) However as someone already said the method probably needs work because i'm trying to change the Datetime value that i get in the first place and add an hour or subtract and etc etc.


That will happen if someone has typed "foo" into the text box, for example. You should use int.TryParse instead, which lets you detect the error without an exception being thrown.

I notice that you're not actually using the return value of your method though - just like you're not using the return value of time.AddHours. You are aware that DateTime.AddHours doesn't actually modify the value you're calling it on, aren't you? (I suspect you'll need to tweak that method quite a bit, actually... there are various potential problems with it, depending on exact what you're trying to do.)

(Finally, I'd change the method name to IncrementHour to comply with .NET conventions.)


you are testing txtHourPlus for emptiness, but then parsing and passing txtHour. typo (?)


If your input isn't parsable as an integer, attempting to parse it will raise an exception. Validate or use Int32.TryParse()


Change this part of your code:

if (txtHour.Text != String.Empty)
{
    int parsedValue;

    if (int.TryParse(txtHour.Text, out parsedValue))
    {
        time1.incrementHour(parsedValue);
    }
    else
    {
        // non-numeric value was entered into the textbox - handle accordingly.
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜