【问题标题】:how to copy a row from a datagridview to another datagridview when cell value change单元格值更改时如何将行从datagridview复制到另一个datagridview
【发布时间】:2019-02-04 13:03:12
【问题描述】:

当我对我的第一个 datagridview1 数据进行更改然后我想复制时,我只想将更改的行数据从 datagridview1 复制到 datagridview2

private void button1_Click(object sender, EventArgs e) {

        string query = @"Select Item.ItemName as item, Stock.SalePrice as 
        Price, invoice.Qty 
        FROM invoice
        JOIN item ON invoice.ItemID = item.ItemID
        JOIN sale ON invoice.SaleID = sale.SaleID
        join Stock on Stock.ItemID  = item.ItemID 
        where sale.SaleID = '" + textBox1.Text + "'";
        SqlDataAdapter SDA = new SqlDataAdapter(query, con);
        DataTable dt = new DataTable();
        SDA.Fill(dt);
        dataGridView1.DataSource = dt;


        DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
        dataGridView1.Columns.Add(btn);
        btn.HeaderText = "Update";
        btn.Text = "Update";
        btn.Name = "btnUpdate";
        btn.UseColumnTextForButtonValue = true;
}

我调用单元格值更改事件,但代码只复制已编辑的行。

请给我代码:

【问题讨论】:

  • 在请人帮助我时,我不会使用“请提供代码”这样的字眼......

标签: c#


【解决方案1】:

datagGridview1CellValueChanged事件中试试这个,

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    DataTable dt = new DataTable();
    if (dataGridView1.DataSource != null)
    {
        dt = (DataTable)dataGridView1.DataSource;
        if (dt.Rows.Count > 0)
        {
            DataRow modifiedRow = dt.Rows[e.RowIndex];

            if (dataGridView2.DataSource != null)
            {
                dt = (DataTable)dataGridView2.DataSource;
                //"Id" is name of the column that has unique, non-nullable values
                if (dt.Rows.Count > 0 && dt.Rows.OfType<DataRow>().Where(x => x["Id"].ToString() == modifiedRow["Id"].ToString()) != null)
                {
                    dt.Rows.Remove(dt.Rows.OfType<DataRow>().Where(x => x["Id"].ToString() == modifiedRow["Id"].ToString()).ToList()[0]);
                }
            }
            else
            {
                dt = new DataTable();
            }
            dt.Rows.Add(modifiedRow);
        }
    }
    dataGridView2.DataSource = dt;
}

希望这会有所帮助...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多