对于TextBox c#应用程序,输入字符串的格式不正确

时间:2019-05-02 02:23:48

标签: c#

我有6个文本框,我想将输入的文本框附加到csv文件中 但它引发错误:输入字符串的格式不正确。

下面的代码可以让任何人重写工作代码

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()); 

2 个答案:

答案 0 :(得分:1)

使用tryparse检查文本框的值是否为有效整数。

尝试一下。

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
}

答案 1 :(得分:0)

该代码期望您的所有文本框都包含有效的整数。如果其中任何一个为空或包含0-9以外的字符,它将抛出该异常。这些字段中的某些听起来像您期望文本输入,而不是整数输入。如果要使用纯文本而不是整数,请使用string代替int,不要使用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}};
...