偶尔“输入字符串格式不正确”错误

时间:2012-01-20 23:41:18

标签: c#

这是我项目中的代码,我运行了一次并且它运行但下次尝试时,它没有错误“输入字符串格式不正确”。急需帮助。

con = new SqlConnection();
con.ConnectionString = ConClass.conString();
string newstud = "SELECT MAX(StudentRegNo) FROM NewStudent";
if (search(newstud) != "")
  RegNo = (int.Parse(search(newstud)) + 1);
else
  RegNo = 1;
lblStuReg.Text = "AP/HQ/" + RegNo.ToString();

4 个答案:

答案 0 :(得分:3)

此特定邮件来自int.Parse调用,因为search(newStudQuery)的结果未返回数字值。要防止这种情况发生,请捕获异常或使用TryParse代替

if (!string.IsNullOrEmpty(queryResult)) {
  if (int.TryParse(search(newStudQuery), out RegNo) {
    RegNo += 1; }
  } else { 
    // Handle the case where the result is not a number
  }
} else {
  RegNo = 1;
}

答案 1 :(得分:2)

此错误很可能意味着search(newstud)确实返回了一个非空的字符串,但也无法将其解析为整数。

我假设search正在执行SQL查询。您应该将结果存储在变量中,否则它会调用它两次并使用int.TryParse来解析结果(它还会使代码更短):

string newStudQuery = "SELECT MAX(StudentRegNo) FROM NewStudent";
string queryResult = search(newStudQuery);
if (!int.TryParse(queryResult, out RegNo))
{
    RegNo = 0;
}
RegNo++;    

答案 2 :(得分:2)

也许你可以简单地查询

string newstud = "SELECT ISNULL(MAX(StudentRegNo) + 1, 1) FROM NewStudent";

...问题听起来像是在应用程序中创建一个id序列 - 这应该通过在数据库中自动递增StudentRegNo来处理。


只是为了锻炼 - 你可以将事情简化为

int RegNo; // assuming you also just declared it somewhere above
int.TryParse(search(newStudQuery), out RegNo);
RegNo++;

但是正如Luke指出的那样,search()也应该被重构以返回更有用的东西,而不是一个可能为空甚至是空引用的字符串。

答案 3 :(得分:0)

这里:

RegNo = (int.Parse(search(newstud)) + 1);

search(newstud)未返回数字。

编辑:使用:

con = new SqlConnection();
con.ConnectionString = ConClass.conString();
string newstud = "SELECT MAX(StudentRegNo) FROM NewStudent";
try{
  RegNo = (int.Parse(search(newstud)) + 1);
}
catch{
  RegNo = 1;
}
lblStuReg.Text = "AP/HQ/" + RegNo.ToString();

编辑:实际上,你应该选择Jared的答案。