错误:(输入字符串格式不正确。)gridview获取中的多个删除

时间:2016-05-14 11:30:21

标签: asp.net

protected void Button1_Click(object sender, EventArgs e)
{
            foreach (GridViewRow grow in GridView1.Rows)
            {
                CheckBox chk = (CheckBox)grow.FindControl("chk1");
                if (chk.Checked)
                {
                    int empid =int.Parse((grow.Cells[0]).Text);
                    deleterecord(empid);
                }
            }
            Bind();
        }



        protected static void deleterecord(int empid)
        {
            SqlConnection con = new SqlConnection("Data Source=desktop-tvrrh2v;Initial Catalog=FROMSQL;Integrated Security=True");
            SqlCommand cmd = new SqlCommand("delete from grrid where id=@id", con);
            cmd.Parameters.AddWithValue("@id",empid);
            con.Open();
            cmd.ExecuteNonQuery();
        }

1 个答案:

答案 0 :(得分:0)

我相信你的代码在这里失败了:

int empid =int.Parse((grow.Cells[0]).Text);

因为(grow.Cells[0]).Text无法解析为int。 我建议你改变这样的代码:

int empid;

if (int.TryParse((grow.Cells[0]).Text, out empid)) {
    // Valid input, do something with it.
    deleterecord(empid);
} else {
    // Not a number, do something else with it.
    //throw error, try to fix state
}

强烈建议您在转换类型时始终使用TryParse