关于输入字符串的格式不正确 Parse()使用

最近用ASP.NET做东西的时候,用到DataGrid,在写更新操作时总是出现 输入字符串的格式不正确
[FormatException: 输入字符串的格式不正确。]
System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +0
的错误。一时想不出办法,搜索了一些东西,无赖多数都是网站上出现的类似的执行错误的页面显示。

后来突然把DataGrid里成绩列为空的项都给填了一遍,居然这次没有报错;分析一下,肯定就是空字符串惹的祸。看起来没问题了。然后,做了做非法数据输入,有出现了类似问题,看来Parse()仅仅是做转换,一旦无法完成该项操作,就会抛出一个错误来,这样原因终于找到了,解决办法也就可以有针对性的作出了,下面列出这个修改后的提交函数

private void btnUpdatelocal_Click(object sender, System.EventArgs e)
{
for (int i=0; i<DataGrid1.Items.Count; i++)
{
DataGridItem _item = DataGrid1.Items[i];
System.Web.UI.WebControls.TextBox qtyTextBox =
(System.Web.UI.WebControls.TextBox)_item.FindControl("txtGrade");

// with a database, we'd use an update command.
// since this is an in-memory datatable, we'll just change the in-memory row.
DataRow dr = ((DataTable)Session["SessionSCS"]).Rows[i];
if(qtyTextBox.Text.ToString()!="")//防止空项转换
{
try
{
dr[4] =int.Parse(qtyTextBox.Text.ToString());
//dr[4] =System.Convert.ToInt32(qtyTextBox.Text.ToString());
}
catch
{
//防止非法输入
}
}
}
DataGrid1.DataSource=((DataTable)Session["SessionSCS"]).DefaultView;
DataGrid1.DataBind();

}

Published At
Categories with Web编程
Tagged with
comments powered by Disqus