-1

我有以下代码运行良好......

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();
}

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

4

1 回答 1

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();
}
于 2013-08-24T17:42:55.237 回答