views:

556

answers:

6

Hi all,

The problem is with the convert of the txt box value, but why?

string strChar = strTest.Substring(0, Convert.ToInt16(txtBoxValue.Text));

Error is: Input string was not in a correct format.

Thanks all.

+5  A: 

txtBoxValue.Text probably does not contain a valid int16.

Otávio Décio
Hope he comes back to accept your answer! (+1)
Andrew Rollings
Hehe, I don't think so :)
Otávio Décio
A: 

You're right! Why didn't I spot that! Time to finish for the day. Thanks

+1 for drive-by. Maybe should have been a comment, but probably didn't deserve the -1.
Andrew Rollings
use the comments, and dont' forget to accept the answer (gives you rep too)
John Sheehan
A: 

A couple reasons the code could be faulty. To really nail it down, put your short conversion on a new line, like this:

short val = Convert.ToInt16(txtBoxValue.Text);
string strChar = strTest.Substring(0, val);

Likely the value in txtBoxValue.Text is not a short (it might be too big, or have alpha characters in it). If it is valid and val gets assigned, then strTest might not have enough characters in it for substring to work, although this normally returns a different error. Also, the second parameter of substring might require an int (not sure, can't test right now) so you may need to actually convert to int32 instead of 16.

What is the value of txtBoxValue.Text during your tests?

DarkwingDuck
+1  A: 

A good way to avoid that error is to use .tryParse (.net 2.0 and up)

int subLength;

if(!int.TryParse(txtBoxValue.Text,out subLength)
   subLength= 0;

string strChar = strTest.Substring(0, subLength);

This way, if txtBoxValue.Textdoes not contain a valid number then subLength will be set to 0;

Loki Stormbringer
+1  A: 

One thing you may want to try is using TryParse

Int16 myInt16;
if(Int16.TryParse(myString, out myInt16)
{
   string strChar = strTest.Substring(0, myInt16);
}
else
{
   MessageBox.Show("Hey this isn't an Int16!");
}
karbon
A: 

ASP.NET offers several validation controls for checking user input. You should use something like a CompareValidator or RegularExpressionValiditor in your WebForm if you're expecting a specific type of input, eg, an Integer.

ob