1

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.

3
  • It would be helpful to post the values of srtTest and txtBoxValue.Text Commented Jan 30, 2009 at 23:10
  • The txtBoxValue was empty! Doh! Commented Jan 30, 2009 at 23:11
  • The question isn't unhelpful. Basic, but not unhelpful. +1 to counter -1. Commented Jan 30, 2009 at 23:16

5 Answers 5

5

txtBoxValue.Text probably does not contain a valid int16.

Sign up to request clarification or add additional context in comments.

Comments

1

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;

Comments

1

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!");
}

Comments

0

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?

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.