Ludovic Migneault
Ludovic Migneault

Reputation: 140

Display that a datagridview's row have been updated/inserted or is in error from a DataTable

I want to display to the user which row in a grid is either in error, updated or inserted.

The grid previously had all the rows and columns managed at hand, but i'm changing it so it's all created/filled with a sqlAdapter(dataTables).

So... I can see if a row have an error or has been inserted... but via the DataRow, with exemple:

usrGrdPieces.getGrid.DataSource.DataSource.GetChanges()

But this only gives me the dataSet to which the grid is binded, not the actual rows of the grid. And I have no idea how I could display the specifics of these rows.

There was previously an added column with an image in it for each of the states the row coulb be in, could it be possible to do even with a grid generated with a bindingSource?

Or if it's possible to just hilight the cell or row in green/red I'd be happy too...

Thanks to anybody that can help!

Upvotes: 0

Views: 3198

Answers (1)

UWSkeletor
UWSkeletor

Reputation: 941

You can get to the DataRow for a row in the grid that is databound to a datatable through the row's DataBoundItem.

For example, let's say I want to highlight in green rows that were added and orange rows that are modified using the DataRowState property that is on a DataRow object. You could do the same thing for displaying an image in a column instead of a backcolor. Error state isn't something that is stored in the data row, so depending on what you mean by that, you'd have to do additional checks. For the purpose of this example, let's say there is a column called "Name" that is supposed to be 50 characters or less. If it is more than that, I'll highlight the row in red, usually I would use the "ErrorText" property for the cell/row to denote there is an error, but I'll stick with the colors for this example.

I'd handle the CellFormatting event (I wrote this in C# since I am more familiar with it, but the properties/concepts are the same in VB).

dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    DataGridView grid = (DataGridView) sender;
    DataRowView currentRowView = (DataRowView) grid.Rows[e.RowIndex].DataBoundItem;
    DataRow currentRow = (DataRow)currentRowView.Row;
    string name = currentRow["Name"].ToString();
    if (name.Length > 50)
    {
        grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
    }
    else if (currentRow.RowState == DataRowState.Added)
    {
        grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Green;
    }
    else if (currentRow.RowState == DataRowState.Modified)
    {
        grid.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Orange;
    }
}

Upvotes: 1

Related Questions