更新gridview中的多行。

时间:2013-08-24 13:56:46

标签: sql-server gridview stored-procedures

我有以下代码正常运行...

protected void btnSubmit_Click(object sender, EventArgs e)
{
    for (int i = 0; i < grdView.Rows.Count; i++)
    {
        GridViewRow row = grdView.Rows[i];
        string trn = ((TextBox)row.Cells[0].FindControl("txtTrn")).Text;
        string remark = ((TextBox)row.Cells[1].FindControl("txtRemark")).Text;
        bool status = ((CheckBox)row.Cells[2].FindControl("ck")).Checked;
        string si = grdView.DataKeys[i].Value.ToString();

        clsDt.sqlCnn.Open();
        SqlCommand cmd = new SqlCommand("USP_MOD_MBRINCDTL", clsDt.sqlCnn);
        cmd.Parameters.Add(new SqlParameter("@ACTION", SqlDbType.VarChar, 20));
        cmd.Parameters.Add(new SqlParameter("@status", SqlDbType.Bit));
        cmd.Parameters.Add(new SqlParameter("@adm_trn", SqlDbType.VarChar, 100));
        cmd.Parameters.Add(new SqlParameter("@remark", SqlDbType.VarChar, 100));
        cmd.Parameters.Add(new SqlParameter("@si", SqlDbType.Int));
        cmd.Parameters["@ACTION"].Value = "UPDATE";
        cmd.Parameters["@status"].Value = status;
        cmd.Parameters["@adm_trn"].Value = trn;
        cmd.Parameters["@remark"].Value = remark;
        cmd.Parameters["@si"].Value = si;
        cmd.CommandType = CommandType.StoredProcedure;
        da=new SqlDataAdapter(cmd);
        ds = new DataSet();
        da.Fill(ds);
        clsDt.sqlCnn.Close();
    }
    BindGrid();
}

但是连接在网格的各行中打开和关闭多次... 是否有更好的方式巧妙地做到这一点......

1 个答案:

答案 0 :(得分:1)

为什么不直接返回一组中的所有数据而不是通过网格循环?

如果失败,请在循环外移动SqlCommand创建和连接打开/关闭

protected void btnSubmit_Click(object sender, EventArgs e)
{
    SqlCommand cmd = new SqlCommand("USP_MOD_MBRINCDTL", clsDt.sqlCnn);
    cmd.Parameters.Add(new SqlParameter("@ACTION", SqlDbType.VarChar, 20));
    cmd.Parameters.Add(new SqlParameter("@status", SqlDbType.Bit));
    cmd.Parameters.Add(new SqlParameter("@adm_trn", SqlDbType.VarChar, 100));
    cmd.Parameters.Add(new SqlParameter("@remark", SqlDbType.VarChar, 100));
    cmd.Parameters.Add(new SqlParameter("@si", SqlDbType.Int));
    cmd.Parameters["@ACTION"].Value = "UPDATE";
    cmd.CommandType = CommandType.StoredProcedure;
    clsDt.sqlCnn.Open();

    for (int i = 0; i < grdView.Rows.Count; i++)
    {
        GridViewRow row = grdView.Rows[i];
        string trn = ((TextBox)row.Cells[0].FindControl("txtTrn")).Text;
        string remark = ((TextBox)row.Cells[1].FindControl("txtRemark")).Text;
        bool status = ((CheckBox)row.Cells[2].FindControl("ck")).Checked;
        string si = grdView.DataKeys[i].Value.ToString();

        cmd.Parameters["@status"].Value = status;
        cmd.Parameters["@adm_trn"].Value = trn;
        cmd.Parameters["@remark"].Value = remark;
        cmd.Parameters["@si"].Value = si;
        da=new SqlDataAdapter(cmd);
        ds = new DataSet();
        da.Fill(ds);

    }
    clsDt.sqlCnn.Close();
    BindGrid();
}