C# string转换为int类型出错

来源:百度知道 编辑:UC知道 时间:2024/06/23 00:11:28
protected void Button1_Click(object sender, EventArgs e)
{
string stuID = Session["user_name"].ToString();
DB db = new DB();
string sqlStr = "select max(id) from [moduleSel]";
DataSet ds = db.getDataSet(sqlStr, "file");
if (ds.Tables[0].Rows.Count == 0)
{
int a = 1;
Label2.Text = a.ToString();
}
else
{
string id = ds.Tables[0].Rows[0].ItemArray[0].ToString();
int a;
a = Int32.Parse(id) + 1;
Label2.Text = a.ToString();
}
}
运行时提示a = Int32.Parse(id) + 1;这句出错..
出错问题:
Input string was not in a correct format.
- -!
小虾请高人解答.....

你数据库里的id是什么类型字段?如果是作为主键用自动递增就可以了啊,然后SQL用排序输出最后一行,应该是最大值吧。
在string id = ds.Tables[0].Rows[0].ItemArray[0].ToString(); 这句加断点看看输出的是什么值。是int的话强转看下
Convert.ToInt32(id) + 1;

int.parse(id)
或者convert.toint32(id)

你调试状态跑一下,看看 id 是不是有效的int 类型的字符串

你这个id是字符串形式的,如果你得到的id 是这样的“23”,用那句肯定不会有错的,但是你要是得到一个"abc"这样的ID号,或者得到一个空的字符串,怎么转都转不用整型的,你还是想办法把id取出来看下,或者就去数据库看看你的id是不是都能转成整型的

是不是类型不对啊

格式不正确是吗?
你可以用string类型的trim方法处理掉两边的空格之类的

还有,Convert.ToInt32我记得就是调用的Parse方法,一个不行另外一个肯定也会出错