views:

861

answers:

4

Hi,

I am using DataGridView Control for reading and writing an XML file through XML Serialization. I have a little pb? as explained below: 1. I read an XMl file and populate a Datagridview controls with deserialized object. 2. I go and update all the values on the datagrid view on the cell. 3. I go and choose the File Save As option without losing focus on the last cell . The value of the particular cell is not updated. If I intentionally lose the focus say I click on another cell on the same grid the value is updated. Can anyone suggest any solution for this?

Thanks, Ashish

+2  A: 

If I understand you correctly, a cell is in editing mode and you're trying to programmatically stop editing and pass the value to the underlying datasource?

I'm using a somewhat "dirty" approach to do that in one of my applications:

if (dataGridView1.CurrentCell.IsInEditMode)    
{    
    int y = dataGridView1.CurrentCellAddress.Y;    
    int x = dataGridView1.CurrentCellAddress.X;    
    if (y > 0)      
        dataGridView1.CurrentCell = dataGridView1.Rows[y - 1].Cells[x];    
    else    
        dataGridView1.CurrentCell = dataGridView1.Rows[y + 1].Cells[x];    
    dataGridView1.CurrentCell = dataGridView1.Rows[y].Cells[x];    
}

That piece of code first checks whether the current cell is in edit mode. Then it changes the current cell programmatically (either to the previous row or the next row in case we're in the first row). After that, it restores the current cell selection.

You would call this code in your "File Save As" handler.

Thorsten Dittmar
Thanks for the solution .
Glad I could help. Could you mark this as your accepted solution?
Thorsten Dittmar
+3  A: 

It's because the edited cell value is not committed to the DataSource until it's validated, which happens when the cell lose focus. If you want to commit the modifications immediately, you can handle the CurrentCellDirtyStateChanged event, and call the CommitEdit method in the handler :

void dataGridView1_CurrentCellDirtyStateChanged(object sender,
    EventArgs e)
{
    if (dataGridView1.IsCurrentCellDirty)
    {
        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}
Thomas Levesque
A: 

You can get the value of a cell which is not yet committed using the EditedFormattedValue property for the current cell, as below

dataGridView1.CurrentCell.EditedFormattedValue

A: 

The best way (though quick and dirty) is to assign the currentCell value to Nothing. Eg: in the save method do:

dgvMyGrid.CurrentCell = Nothing

and then proceed further

Amit Karmakar