更新DataGridView选定的行

时间:2017-07-25 09:43:13

标签: c# datagridview rows selected

我尝试更新DataGridView中的选定行,但结果很奇怪,它总是缺少一行或另一行。问题是当我单击btnSettled按钮设置结算日期,然后单击btnUpdate更新数据库,结果似乎没问题,但是点击btnRefresh刷新DGV后,总会有一个缺失的行。这是UpdateCommand或foreach循环的问题吗?请帮我解决这个问题。谢谢。

点击btnSettle之前 before click btnSettled

点击btnSettled和btnUpdate后 after click btnSettled and btnUpdate

点击btnRefresh后 after click btnRefresh

我的代码如下:

DataTable dtTrx = new DataTable();
SqlDataAdapter daTrx = new SqlDataAdapter();
DataSet dsTrx = new DataSet();

    public Form1()
    {
        InitializeComponent();
        getData();
    }

    private void getData()
    {
        string strConn = "Data Source=.\\xpw;Initial Catalog=MyStock;Integrated Security=True;";
        SqlConnection conn = new SqlConnection(strConn);
        conn.Open();

        string sqlTrx = "SELECT TrxID, TrxDate,Ticker,Qty,Price,Type,AccID, SettledDate,BrokerUserID FROM Trx";

        daTrx = new SqlDataAdapter(sqlTrx, conn);
        SqlCommandBuilder cbTrx = new SqlCommandBuilder(daTrx);
        daTrx.Fill(dsTrx, "trx");

        conn.Close();

        dtTrx = dsTrx.Tables["trx"];
        dgvTrx.DataSource = dtTrx;
    }

    private void btnUpdate_Click(object sender, EventArgs e)
    {
        daTrx.Update(dsTrx, "trx");
    }

    private void btnRefresh_Click(object sender, EventArgs e)
    {
        dsTrx.Clear();
        daTrx.Fill(dsTrx, "trx");
    }

    private void btnSettled_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewCell c in dgvTrx.SelectedCells)
        {
            dgvTrx[7, c.RowIndex].Value = "2017/7/23";
        }
    }

2 个答案:

答案 0 :(得分:1)

首先,您需要开始使用参数化SQL查询。

其次,我没有看到您的代码出现问题,但您尝试了这个:

private void btnSettled_Click(object sender, EventArgs e)
{
    foreach (DataGridViewRow r in dgvTrx.SelectedRows)
    {
        r.Cells["SettledDate"].Value = "2017/7/23"; //use the column name instead of column index
    }
    this.BindingContext[dgvTrx.DataSource].EndCurrentEdit(); 
    //the above line is added to improve the solution
    //as per the link mentioned in the accepted answer
}

这种方法背后的原因是,即使您更改列位置,您也不必重新编写代码以匹配更改

当您使用SelectedCells时,除非您的鼠标被拖到最后Cell,否则它不会被添加到SelectedCell集合中

注意:在r.Cells["SettledDate"].Value中我假设列名为SettledDate

答案 1 :(得分:0)

最后我找到了解决方案:

Programmingly udpating selected rows misses the last one in dgv.DataSource.GetChanges()?

它只需要在foreach循环后结束编辑最后一行:

this.BindingContext[dgvTrx.DataSource].EndCurrentEdit();       

再次感谢@Nobody。