Good day people of stackoverflow,
I am building a GUI and in this GUI I have a datagridview which shows data from a database. However I am looking for a way to change the color of an entire row to red when the first column of that row holds the string "Aborted".
I've tried finding a solution to this, however all examples have been conditions with Integers instead of Strings.
This is my current piece of code for the coloring:
private void datagridview1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 1 && e.Value as string == "Aborted")
{
var style = datagridview1.Rows[e.RowIndex].DefaultCellStyle;
style.BackColor = Color.Red;
style.ForeColor = Color.White;
}
}
However this does not change the color of the column or the entire row that holds the value Aborted nor does it even give an error message...
Even in the Events Properties of the datagridview1
next to CellFormatting
it shows datagridview1_CellFormatting
so it surely is bound to the datagridview.
Screenshot Events Properties of the datagridview1
Screenshot of the datagridview enter image description here
Does anyone have a solution to this? I have absolutely no idea what is going wrong.
EDIT: quick screenshot of an error Error of @Jimi's example
CodePudding user response:
You are manipulating the wrong style object. Try this:
private void datagridview1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 1 && e.Value as string == "Aborted")
{
e.CellStyle.BackColor = Color.Red;
e.CellStyle.ForeColor = Color.White;
}
}
CodePudding user response:
The solution of Oliver works great if you wish to only color the column that has "Aborted", however the solution to color the entire row is as follows (Many thanks to u/JTarsier from Reddit)
// Use the event CellFormatting from Datagridview > Properties > Events
private void datagridview1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// Use this one liner to check which number is associated with which column
//(so you don't make the mistake of trying to use the wrong column like me ._.)
// Debug.WriteLine($"{e.ColumnIndex} : '{e.Value}'");
if (e.ColumnIndex == 0 && e.Value as string == "Aborted")
{
var style = datagridview1.Rows[e.RowIndex].DefaultCellStyle;
style.BackColor = Color.Red;
style.ForeColor = Color.White;
}
}
Thanks for all the help!