且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用复选框更新数据库中一列中的多个数字

更新时间:2022-12-11 20:23:37

您可以尝试一次吗?没有重大代码更改.只是尝试在循环的每次迭代中初始化命令对象.

Can you try this once? No major code change. just trying to initialize command object in each iteration of the loop.

protected void btncast_Click(object sender, EventArgs e)
        {
            StringBuilder strSql = new StringBuilder(string.Empty);
            SqlConnection con = new SqlConnection(strConnection);
            SqlCommand cmd;
 
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                CheckBox chkselect = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("chkselect");
                if (chkselect != null)
                {
                    if (chkselect.Checked)
                    {
                        string strID = GridView1.Rows[i].Cells[0].Text;
        
                        try
                        {
                            cmd = new SqlCommand();
                            const string strUpdate = "Update Candidate_list set total_counts = total_counts+1 WHERE pic_id = @pic_id";
                            cmd.CommandType = CommandType.Text;
                            cmd.CommandText = strUpdate.ToString();
                            cmd.Parameters.Clear();
                            cmd.Parameters.AddWithValue("@pic_id", strID);
                            cmd.Connection = con;
                            con.Open();
                            cmd.ExecuteNonQuery();
                        }
                        catch (SqlException ex)
                        {
                            string errorMsg = "Error in Updation";
                            errorMsg += ex.Message;
                            throw new Exception(errorMsg);
                        }
                      finally
                        {
                            con.Close();
                            Response.Redirect("~/Voting.aspx/");
                        }
                       
                    }
                }
            }
        }
    }