关于string“null”转换为int型的0
protected void Button2_Click(object sender, EventArgs e){
DB db=new DB();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow gRow = GridView1.Rows[i];
string cj1 = ((Label)GridView1.Rows[i].Cells[0].FindControl("label1")).Text;
string cj2 = ((Label)GridView1.Rows[i].Cells[3].FindControl("label2")).Text;
string cj3 = ((Label)GridView1.Rows[i].Cells[6].FindControl("label3")).Text;
if (cj1!=null)
{
string chengji1 = ((TextBox)gRow.FindControl("TextBox1")).Text;
if (chengji1 == "0" || chengji1 == null)
{
chengji1 = "0";
}
string sqlstr1 = "update chengji set chengji=" + Convert.ToInt32(chengji1) + "where xuehao=" + Convert.ToInt32(cj1) + " and xueke='" + Convert.ToString(ViewState["xueke"]) + "' and xueqi=" + Convert.ToInt32(ViewState["xueqi"]) + " and haoxu=" + Convert.ToInt32(ViewState["haoxu"]);
db.sqlex(sqlstr1);
}
if (cj2!=null)
{
string chengji2 = ((TextBox)gRow.FindControl("TextBox2")).Text;
if (chengji2 == "0" || chengji2 == null)
{
chengji2 = "0";
}
string sqlstr2 = "update chengji set chengji=" + Convert.ToInt32(chengji2) + "where xuehao=" + Convert.ToInt32(cj2) + " and xueke='" + Convert.ToString(ViewState["xueke"]) + "' and xueqi=" + Convert.ToInt32(ViewState["xueqi"]) + " and haoxu=" + Convert.ToInt32(ViewState["haoxu"]);
db.sqlex(sqlstr2);
}
if (cj3!=null)
{
string chengji3 = ((TextBox)gRow.FindControl("TextBox3")).Text;
if (chengji3 == "0" || chengji3 == null)
{
chengji3 = "0";
}
string sqlstr3 = "update chengji set chengji=" + Convert.ToInt32(chengji3) + "where xuehao=" + Convert.ToInt32(cj3) + " and xueke='" + Convert.ToString(ViewState["xueke"]) + "' and xueqi=" + Convert.ToInt32(ViewState["xueqi"]) + " and haoxu=" + Convert.ToInt32(ViewState["haoxu"]);
db.sqlex(sqlstr3);
}
}
Response.Write("<script>alert('数据保存成功');</script>");
}
如果文本框的植为空的话红色部分sql语句会提示出错,我对文本框里的值作了判断,为空就赋予“0”,可是我知道Convert.ToInt32(chengji3)这样也是会有问题的,怎么办啊?chengji表里的字段chengji为int型,允许空值。。
[ 本帖最后由 fyz520 于 2010-12-6 09:29 编辑 ]