user824911
user824911

Reputation: 125

DataGridView Save Changes On Row Change

I am attempting to save a record after leaving the row in a DataGridView.

I have seen solutions use the RowValidated event, however, when the rows are sorted then the record gets resorted before the RowValidation event is fired. I also attempted to get the row using the BindingSource Current property, but the current property is already changed. Same applies to RowLeaving I believe.

I have tried using the RowChanged event on the datatable directly and that does work OK.

I ended up using the RowValidation event and getting the changes from the datatable (GetChange()), but this doesn’t seem idea.

In addition for deletes I used the UserDeletingRow event, but again this doesn’t seem idea.

What is the best way for saving records after leaving the row?

Upvotes: 7

Views: 16264

Answers (2)

spajce
spajce

Reputation: 7082

Have you tried the DataGridView.RowValidating Event and .IsCurrentRowDirty?

    private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
    {
        if (dataGridView1.IsCurrentRowDirty)
        {
           //Do stuff
        }
    }

Upvotes: 5

Chris Ballance
Chris Ballance

Reputation: 34337

Have you taken a look at .RowLeave?

private void dataGridView1_RowEnter(object sender, 
    DataGridViewCellEventArgs e)
{
    for (int i = 0; i < dataGridView1.Rows[e.RowIndex].Cells.Count; i++)
    {
        dataGridView1[i, e.RowIndex].Style.BackColor = Color.Yellow;
    }
}

private void dataGridView1_RowLeave(object sender, 
    DataGridViewCellEventArgs e)
{
    for (int i = 0; i < dataGridView1.Rows[e.RowIndex].Cells.Count; i++)
    {
        dataGridView1[i, e.RowIndex].Style.BackColor = Color.Empty;
    }
}

source: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rowleave.aspx

Upvotes: 3

Related Questions