在Datagridview中选择行执行存储过程

时间:2018-12-19 16:09:15

标签: c# winforms stored-procedures datagridview

不确定为什么我弄错了。

尝试在datagridview中选择行并将它们传递给存储过程。每次执行以下命令时,都会传递正确的行数,但是例如而不是第4行,它将在第1行执行查询。或者如果我选择了2。如何将所选的行传递给查询,而不仅仅是所选的行数是多少?

foreach (DataGridViewRow r in dataGridView1.SelectedRows)
{
    for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
    {
        SqlCommand sqlCmd = new SqlCommand("uspSelectWater", con);
        sqlCmd.CommandType = CommandType.StoredProcedure;

        sqlCmd.Parameters.AddWithValue("@CaseNumberKey", this._CaseNum);
        sqlCmd.Parameters.AddWithValue("@MasterAccount", dataGridView1.Rows[i].Cells[3].Value);
        sqlCmd.Parameters.AddWithValue("@WaterAccount", dataGridView1.Rows[i].Cells[4].Value);
        sqlCmd.Parameters.AddWithValue("@OwnerName", dataGridView1.Rows[i].Cells[5].Value);
        sqlCmd.Parameters.AddWithValue("@MailName", dataGridView1.Rows[i].Cells[6].Value);
        sqlCmd.Parameters.AddWithValue("@AcctBalance", dataGridView1.Rows[i].Cells[7].Value);

        sqlCmd.ExecuteNonQuery();
    }   
}

2 个答案:

答案 0 :(得分:2)

您已经在循环选择的行,因此不需要内部循环。

只需使用选定的行

尝试一下:

foreach (DataGridViewRow r in dataGridView1.SelectedRows)
{    

        SqlCommand sqlCmd = new SqlCommand("uspSelectWater", con);
        sqlCmd.CommandType = CommandType.StoredProcedure;

        sqlCmd.Parameters.AddWithValue("@CaseNumberKey", this._CaseNum);
        sqlCmd.Parameters.AddWithValue("@MasterAccount", r.Cells[3].Value);
        sqlCmd.Parameters.AddWithValue("@WaterAccount", r.Cells[4].Value);
        sqlCmd.Parameters.AddWithValue("@OwnerName", r.Cells[5].Value);
        sqlCmd.Parameters.AddWithValue("@MailName", r.Cells[6].Value);
        sqlCmd.Parameters.AddWithValue("@AcctBalance", r.Cells[7].Value);

        sqlCmd.ExecuteNonQuery();

}

答案 1 :(得分:0)

使用类似这样的方法读取值,然后传递给存储过程:

int i;
i = dg.SelectedCells[0].RowIndex;
str1= dg.Rows[i].Cells[1].Value.ToString();
str2= dg.Rows[i].Cells[2].Value.ToString();
相关问题