【问题标题】:Select rows in Datagridview execute stored procedure在 Datagridview 中选择行执行存储过程
【发布时间】:2018-12-19 16:09:15
【问题描述】:

不知道为什么我弄错了。

试图在 datagridview 中选择行并将它们传递给存储过程。每次执行以下操作时,都会传递正确的行数,但例如,它将在第 1 行执行查询,而不是第 4 行。或者如果我选择了 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();
    }   
}

【问题讨论】:

  • 你不需要那个内循环。 A Row 有一个 Index 属性——你必须使用它。否则就是r.Cells[3].Value

标签: c# winforms stored-procedures datagridview


【解决方案1】:

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

只使用选定的行

试试这个:

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

}

【讨论】:

  • 非常感谢。完美运行!
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2013-03-12
    • 2013-01-08
    • 2017-06-21
    • 2010-09-15
    • 2014-12-07
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    相关资源
    最近更新 更多