user11437064
user11437064

Reputation:

Input string was not in a correct format for TextBox c# application

I have 6 Text boxes and i want to append the textboxes entered text to a csv file but it throws error : Input string was not in a correct format.

below is the code can any one rewrite the working code

String filePath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.FullName,"fetching.csv");
String strSeperator=",";
StringBuilder sbOutput = new StringBuilder();

int env = Convert.ToInt32(textBox1.Text); //error is throwing from this line
int user = Convert.ToInt32(textBox2.Text);//error is throwing from this line
int pass = Convert.ToInt32(textBox3.Text);//error is throwing from this line
int host = Convert.ToInt32(textBox4.Text);//error is throwing from this line
int port = Convert.ToInt32(textBox5.Text);//error is throwing from this line
int service = Convert.ToInt32(textBox6.Text);//error is throwing from this line     

int[][] inaOutput = new int[][]{new int[]{env,user,pass,host,port,service}};
int ilength = inaOutput.GetLength(0);
for(int i=0;i<ilength;i++)
sbOutput.AppendLine(String.Join(strSeperator,inaOutput[i]));

File.AppendAllText(filePath,sbOutput.ToString()); 

Upvotes: 0

Views: 386

Answers (2)

Exequiel
Exequiel

Reputation: 13

Use tryparse to check if the value of the textbox is valid integer.

try this.

int env = 0 ,user = 0,pass = 0,host = 0,port = 0,service = 0;

if(!Int32.TryParse(txt1.Text, out env) || 
   !Int32.TryParse(txt2.Text, out user) ||
   !Int32.TryParse(txt3.Text, out pass) ||
   !Int32.TryParse(txt4.Text, out host) ||
   !Int32.TryParse(txt5.Text, out port) ||
   !Int32.TryParse(txt6.Text, out service))
{
   //Not all is valid
}

Upvotes: 1

Tim
Tim

Reputation: 6060

That code is expecting all of your text boxes to contain valid integers. If any of them are blank or contain characters other than 0-9, it'll throw that exception. Some of those fields sounds like you expect text input, instead of integer inputs. If you want plain text instead of integers, use string instead of int and don't Convert.ToInt32()

string env = textBox1.Text;
string user = textBox2.Text;
string pass = textBox3.Text;
string host = textBox4.Text;
string port = textBox5.Text;
string service = textBox6.Text;

string[][] inaOutput = new string[][]{new string[]{env,user,pass,host,port,service}};
...

Upvotes: 0

Related Questions