Alex Hunt
Alex Hunt

Reputation: 54

DataGridView cell color not changing on error

I'm trying to edit the BackColor of a DataGridViewCell to display as red when the user inputs a value that is incorrect.

    private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
    {
        if (e.Exception is FormatException)
        {
            dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Red;
        }

    }

The color doesn't actually update for reasons I don't understand. It works fine editing ANY other cell just not the selected one.

Upvotes: 1

Views: 664

Answers (1)

Angua
Angua

Reputation: 26

I don't know your code but maybe you need to think again about the logic of the program. It depends from where the exception is coming. If is from a place where the text is not set, there is no way and the color to be changed. DataError is exception so the code after is thrown is not running. I think that DataError doesn't have the info for every exception about that in which cell is the exception. so it's possible that you don't change color because of that.

I don't know your code so I can't help much. But I'll tell you how I would do it.

I'll make a function to check the user inputs and I'll call it in datagridview CellValidating event and change color there if the input is not correct

Upvotes: 1

Related Questions