blah blah blah is here! blah blah » Close

up1down
link

I have a datagridview with a column called "status" that loads a value from a database, i'm trying to change the back color of the row to yellow if there's the value of "cleaned" in the 'status' column.

I'll put the function in my form load event, whats the best way of doing this?

last answered one year ago

2 answers

link

This should work:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow) break;
object obj = row.Cells["status"].Value;
if (obj != null && !DBNull.Value.Equals(obj))
{
string content = obj.ToString().ToLower();
if (content == "cleaned")
{
row.DefaultCellStyle.BackColor = Color.Yellow;
}
}
}

up0down
link

Thanks vulpes - although i think i may have something set up wrong, i cant get that code to work correct, and as i'm sure your code is fine it must be the way i'm executing it, i can get it to change only the first row yellow if i adapt it as follows:

foreach (DataGridViewRow row in usedDataGridView.Rows)
{
if (row.IsNewRow) break;
object obj = row.Cells[2].Value;
if (obj != null && !DBNull.Value.Equals(obj))
{
//string content = obj.ToString().ToLower();
if (row.Cells[2].Value == "CLEANED")
{
row.DefaultCellStyle.BackColor = Color.Yellow;
}
}
}




this.usedTableAdapter.Fill(this.usedDataSet.used);
//inserted code here

vulpes
17279

Yes, I tried the code and it worked fine. Are you sure you're placing the code AFTER the code which binds the DGV to your database table in Form_Load?

I've inserted it below the code in my edited answer? just one other thing, i have to apply the column name like so [2] otherwise it throws an error saying column name not found?

vulpes
17279

The problem appears to be that you're inserting the code after the datatable has been filled but before it's been bound to the DGV which is therefore empty at the time. You should have a line like this somewhere: dataGridView1.DataSource = this.usedDataSet.used; and the new code needs inserting after that.

My datagridview is created by visual studio from the toolbar dragged onto the form, would that make a difference?

Ahh -yes vulpes i got it working, it was a typo on the data in the field :) thanks for your help.

Feedback