简体   繁体   中英

Complete Adding Row in DataGridView

I'm sure that there's a simple answer to this but for the life of me I can't see it:

I have a DataGridView bound to a DataTable. One of the cells can contain fairly lengthy strings so I've created a editor dialog window (which also does some validation etc.) which opens on the DataGridView's CellDoubleClick. When the user clicks ok on the editor dialog the value gets put in the cell.

This works fine as long as it's a cell that has already being added to the DataGridView, but if I do it on the "add new row" (where DataGridViewRow.IsNewRow is true) then when the dialog is closed I have the double problem of the edited string not being displayed unless the row is in edit mode AND subsequently not being able to add a new row.

One potential solution I can see is ensuring that the new row is added to the underlying source before I open the dialog window but I can't see an elegant way to do that (DataGridView.EndEdit() doesn't do it). So is there a neat way to do that (or alternatively is there a better solution altogether)?

Code goes something like this:

void DataGridViewCellCoubleClick(object sender, DataGridViewCellEventArgs e){
    DataGridView gridview = (DataGridView)sender;
    gridview.EndEdit();
    EditForm editForm = new EditForm(gridview.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());

    if(editForm.ShowDialog() == DialogResult.OK){
        gridview.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = editForm.StringResult;
    }

}

EDIT:

I found a solution which achieves what I require:

Before calling :

DataGridView.EndEdit()

I also check for the current row to be "IsNewRow" and if it is I use

DataGridView.NotifyCurrentCellDirty(true)

Which adds it before I open my edit window. Hope that helps someone.

I think the problem is with the way that you have bound the Data Table to the Data GridView.

I would create a binding source and set its Datasource to the DataTable. I would then Set The Data Source for your Datagrid View as the Binding Source.

When you add a new row in the Datagrid View, create a new row in your datatable, then refresh the Datatable.

Those changes should reflect through in the Datagrid view as they are both bound by the Binding source.

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