简体   繁体   中英

Dynamically adding row to datatable adds two rows

I have a DataGridView 'DGV_MachinesExclusion' that's bound to a DataTable 'ExcludedMachines'. When manually adding a new row in the DataGridView I use the CellValueChanged event of the DataGridView to trigger the code below.

        private void DGV_MachinesExclusion_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        DataRow dr = ExcludedMachines.NewRow();
        dr = ((DataRowView)DGV_MachinesExclusion.Rows[0].DataBoundItem).Row;
        ExcludedMachines.Rows.Add();
        UpdateExlusionList();
    }

The result is that it adds two rows. One blank row and one row with the manually added data. The method 'UpdateExclusionList()' just write the DataTable to an XML file. I have used this way of dynamically adding rows succesfully in the past. Can anyone explain why this code adds two rows?

Thx, Thomas

The line

 ExcludedMachines.Rows.Add();

would add a blank row because you haven't specified in the 'add' function what to add to the rows - you should put

ExcludedMachines.Rows.Add(dr);

instead to populate that row.

When you're triggering the event, is it changing the cell value that triggered it (ie is it firing the event more than once when you expect it to only run once)? And have you double checked the 'UpdateExclusionList()' method that it definitely doesn't contain any addition row creation code by accident (left in from a test possibly?)?

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM