Datagridview colour changing - c#

I'm trying to change the colour based on the value in the cell, complete or incomplete but for some reason it's saying that 'Color' doesn't exist in the current context.
Is there a system item I should be using or something?
If anyone has any alternatives to what I'm trying to do that would also be appreciated.
foreach (DataGridViewRow row in dtaFinished.Rows)
{
string RowType = row.Cells[4].Value.ToString();
if (RowType == "Completed")
{
row.DefaultCellStyle.BackColor = Color.Green; //Error on these lines
row.DefaultCellStyle.ForeColor = Color.White; //Error on these lines
}
else if (RowType == "Incomplete")
{
row.DefaultCellStyle.BackColor = Color.Yellow;
row.DefaultCellStyle.ForeColor = Color.Black;
}
}

use the below namespace:
using System.Drawing;
hope thiS will help.

Hi You can found your answere Here

I used this in a project a while back :-
private void dgvOutstandingReports_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
int colIndex = e.ColumnIndex;
int rowIndex = e.RowIndex;
if (rowIndex >= 0 && colIndex >= 0)
{
DataGridViewRow theRow = dgvOutstandingReports.Rows[rowIndex];
if (theRow.Cells[colIndex].Value.ToString() == "Daily Report")
{
theRow.DefaultCellStyle.BackColor = Color.LightYellow;
}
else if (theRow.Cells[colIndex].Value.ToString() == "Monthly Report")
{
theRow.DefaultCellStyle.BackColor = Color.LightGray;
}
else if (theRow.Cells[colIndex].Value.ToString() == "SMP Report")
{
theRow.DefaultCellStyle.BackColor = Color.Snow;
}
else if (theRow.Cells[colIndex].Value.ToString() == "Weekly Report")
{
theRow.DefaultCellStyle.BackColor = Color.Pink;
}
else if (theRow.Cells[colIndex].Value.ToString() == "Hourly Report")
{
theRow.DefaultCellStyle.BackColor = Color.LightSteelBlue;
}
}
}

Related

Change row color in datagridview

I know it's already been written about.
Everything looks very good. But when I move to the right to see the rest of the columns, the rows in DataDridView start blinking very much. I can't solve this.
private void registersDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridViewRow rowDataGridView = null;
string dataPropertyName;
dataPropertyName = this.registersDataGridView.Columns[e.ColumnIndex].DataPropertyName;
int isApprovedColumnIndex = this.registersDataGridView.Columns[isApprovedColumnName].Index;
int isCancelledColumnIndex = this.registersDataGridView.Columns[isCancelledColumnName].Index;
bool theColorHasBeenSet = false;
if (e.RowIndex >= 0 && e.RowIndex != btregisterDgvRowIndex)
{
rowDataGridView = this.registersDataGridView.Rows[e.RowIndex];
if (this.registersDataGridView.Columns[isCancelledColumnIndex].DataPropertyName == "IsCancelled")
{
if (rowDataGridView.Cells[isCancelledColumnIndex].Value != null && rowDataGridView.Cells[isCancelledColumnIndex].Value.ToString() == "Tak")
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.PaleVioletRed)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.PaleVioletRed;
}
theColorHasBeenSet = true;
}
else
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.Ivory)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.Ivory;
}
}
btregisterDgvRowIndex = e.RowIndex;
}
if (this.registersDataGridView.Columns[isApprovedColumnIndex].DataPropertyName == "IsApproved")
{
if (!theColorHasBeenSet)
{
if (rowDataGridView.Cells[isApprovedColumnName].Value != null && rowDataGridView.Cells[isApprovedColumnName].Value.ToString() == "-")
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.LightGray)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.LightGray;
}
theColorHasBeenSet = true;
}
else if (rowDataGridView.Cells[isApprovedColumnName].Value != null && rowDataGridView.Cells[isApprovedColumnName].Value.ToString() == "Nie")
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.PaleVioletRed)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.PaleVioletRed;
}
theColorHasBeenSet = true;
}
else
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.Ivory)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.Ivory;
}
}
btregisterDgvRowIndex = e.RowIndex;
}
}
}
}
else
{
if (rowDataGridView.DefaultCellStyle.BackColor != Color.Ivory)
{
rowDataGridView.DefaultCellStyle.BackColor = Color.Ivory;
}
}
You're not setting the theColorHasBeenSet here which might cause it to change between Ivory and the next color on your list.
Your code seems to verbose to me, try the following
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.RowIndex < 0)
return;
var rowDataGridView = this.registersDataGridView.Rows[e.RowIndex];
Color GetBackgroundColor()
{
var isApprovedColumnIndex = this.registersDataGridView.Columns[isApprovedColumnName].Index;
var isCancelledColumnIndex = this.registersDataGridView.Columns[isCancelledColumnName].Index;
if (this.registersDataGridView.Columns[isCancelledColumnIndex].DataPropertyName == "IsCancelled")
{
var strValue = Convert.ToString(rowDataGridView.Cells[isCancelledColumnIndex].Value);
if (strValue == "Tak")
return Color.PaleVioletRed;
}
if (this.registersDataGridView.Columns[isApprovedColumnIndex].DataPropertyName == "IsApproved")
{
var strValue = Convert.ToString(rowDataGridView.Cells[isApprovedColumnIndex].Value);
if (strValue == "-")
return Color.LightGray;
if (strValue == "Nie")
return Color.PaleVioletRed;
}
return Color.Ivory;
}
rowDataGridView.DefaultCellStyle.BackColor = GetBackgroundColor();
}

Change row color based on text in column

I'm trying to change the color of the row in a datagridviewer based on the text that is in one of the columns. I'm getting the error: Object reference not set to an instance of an object on the line of the first if statement. I filled in the datagridviewer based on a datasource which the code is also below.
void ChangeDataGridViewColor()
{
foreach (DataGridViewRow Row in datagridviewTreatmentPrep.Rows)
{
if (Row.Cells["Primary Onc"].Value.ToString() == "JMK")
{
Row.DefaultCellStyle.BackColor = Color.Green;
}
if (Row.Cells["Primary Onc"].Value.ToString() == "DBF")
{
Row.DefaultCellStyle.BackColor = Color.Orange;
}
else
{
Row.DefaultCellStyle.BackColor = Color.White;
}
}
}
void FillDataGridViewTreatmentPrep()
{
string constring = "datasource = RadOncViewerDatabase.db";
string TreatPrepQuery = "SELECT * FROM TreatmentPrep";
SQLiteConnection connectionstring = new SQLiteConnection(constring);
connectionstring.Open();
DataTable dsTreatPrep = new DataTable();
SQLiteDataAdapter adapterTreatPrep = new SQLiteDataAdapter(TreatPrepQuery, constring);
adapterTreatPrep.Fill(dsTreatPrep);
datagridviewTreatmentPrep.DataSource = dsTreatPrep;
//datagridviewTreatmentPrep.BindingContext = new BindingContext();
//this.datagridviewTreatmentPrep.DataSource = dsTreatPrep.Tables[0].DefaultView.ToTable(true, "Patient_Name");
}
Use the the RowPrePaint event, and don't use .ToString() on objects that can be null:
private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
if (e.RowIndex < 0) return;
var row = (sender as DataGridView).Rows[e.RowIndex];
string value = Convert.ToString(row.Cells["Primary Onc"].Value);
//or in VS 2015: string value = row.Cells["Primary Onc"].Value?.ToString();
if (value == "JMK")
row.DefaultCellStyle.BackColor = Color.Green;
else if (value == "DBF")
row.DefaultCellStyle.BackColor = Color.Orange;
else
row.DefaultCellStyle.BackColor = Color.White;
}
Below is the code I have tested and it works as expected. Sorry for the delay.
foreach (DataGridViewRow Row in dataGridView1.Rows) {
DataRowView drv = (DataRowView)Row.DataBoundItem;
if (drv != null) {
if (drv.Row["Primary Onc"].ToString() == "JMK") {
Row.DefaultCellStyle.BackColor = Color.Green;
}
else {
if (drv.Row["Primary Onc"].ToString() == "DBF") {
Row.DefaultCellStyle.BackColor = Color.Orange;
}
else {
Row.DefaultCellStyle.BackColor = Color.White;
}
}
}
}
Hope this helps.
you must use DataGridViewCellStyle class
my solution:
int max = dgv.Rows.Count;
DataGridViewCellStyle style;
for (int i = 0; i < max; i++)
for (int j = 2; j < dgv.Columns.Count; j++)
if (dgv[j, i].Value.ToString() == "")
{
style = dgv[j, i].Style;
style.BackColor = Color.Red;
dgv[j, i].Style = style;
}

How can I color rows in datagridview with condition C#

I want with a condition :
all rows have bool_badge =0 : color with RED
all rows have bool_badge=1 : color with ForestGreen
I have a code Correct BUT just when i click for a cell specific
My code:
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
int row = this.dataGridView1.CurrentCell.RowIndex;
string valeur = dataGridView1[2, row].Value.ToString();
if (valeur == "0")
{
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red;
}
else
{
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.ForestGreen;
}
}
The Result :
1) `
2)
But I want when i execute my application , the test begin if bool_badge 0 or 1, and i have for all the gridview : color RED or ForestGreen ,
I try this code:
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string valeur = dataGridView1[2, i].Value.ToString();
if (valeur == "0")
{
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red;
}
else
{
dataGridView1.DefaultCellStyle.SelectionBackColor = Color.ForestGreen;
}
}
But i have ERROR!
this is :
How can i fix it?
Very thanks,
You can use Datagridview's Cell_Formatting event.
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].HeaderText == "bool_badge" && dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
// if the column is bool_badge and check null value for the extra row at dgv
{
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "0")
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
}
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "1")
{
dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.ForestGreen;
}
}
}
Result will be,
Hope helps,
You should use .Rows and .Cells properties.
string valeur = dataGridView1.Rows[i].Cells[2].Value.ToString();
For helping you debugging don't do Value.ToString(); just
var value = dataGridView_XXX.Rows[rowNumber].Cells[i].value;
And
if (value == null) display your row/column index
else dataGridView_XXX.Rows[rowNumber].DefaultCellStyle.BackColor = xxx;

Filter Criteria % like % following Code

i use this code for focus row which match text in search text box.now how can i use % like % criteria for this code
foreach (DataGridViewRow row in GdvDetails.Rows)
{
var cellValue = row.Cells["Bunch Component"].Value;
if (cellValue != null && cellValue.ToString() == txtSearch.Text)
{
GdvDetails.Rows[row.Index].DefaultCellStyle.BackColor = Color.Yellow;
}
else
{
GdvDetails.Rows[row.Index].DefaultCellStyle.BackColor = Color.Empty;
}
}
try this
foreach (DataGridViewRow row in GdvDetails.Rows)
{
var cellValue = row.Cells["Bunch Component"].Value;
if (cellValue != null)
{
if ( cellValue.ToString().Contains(txtSearch.Text))
{
GdvDetails.Rows[row.Index].DefaultCellStyle.BackColor = Color.Yellow;
}
else
{
GdvDetails.Rows[row.Index].DefaultCellStyle.BackColor = Color.Empty;
}
}
}

Cell Formatting In DataGridView On DataBindingComplete

I am having problems with a requirement on one of my projects at work. What I am doing is binding a datatable to a DataGridView(DGV)'s datasource. I then loop through the DataGridView and check if the cell as either 1 * or 2 ** in its value and format those cells with a tooltip and a red background. If I use a button event to trigger this everything works perfectly fine. But if I want this to occur automatically when the form loads using the DataBindingComplete event it does not work correctly. The problem was DataBindingComplete was firing multiple times. I read this SO question which gave me a couple options to try and none worked. Here is the code:
public partial class TestForm2 : Form
{
private DataTable dt;
private int methodCalls = 0;
private bool isFormatted = false;
public TestForm2()
{
InitializeComponent();
buildDataTable();
dataGridView1.DataBindingComplete += dataGridView1_DataBindingComplete;
}
private void TestForm2_Load(object sender, EventArgs e)
{
bindData();
}
private void button1_Click(object sender, EventArgs e)
{
formatDataGridView();
}
private void bindData()
{
dataGridView1.DataSource = dt;
}
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
//If this code is commented out the program will work just fine
//by just clicking the button
//This was added to prevent formatDataGridView from executing more
//than once. Even though I unreg and rereg the event handler, the
//method was still being called 3 - 4 times. This successfully
//prevented that but only the *'s were removed and no red back color
//added to the cells.
if(!isFormatted)
{
formatDataGridView();
}
}
private void buildDataTable()
{
dt = new DataTable();
dt.Columns.Add("col1");
dt.Columns.Add("col2");
dt.Columns.Add("col3");
dt.Columns.Add("col4");
Random randNum = new Random();
for(int i = 0; i < 10; i++)
{
DataRow dr;
object[] rowItems = new object[dt.Columns.Count];
for(int j = 0; j < dt.Columns.Count; j++)
{
int number = randNum.Next(1, 20);
if(number % 7 == 0)
{
rowItems[j] = number + "*";
}
else if(number % 5 == 0)
{
rowItems[j] = number + "**";
}
else
{
rowItems[j] = number;
}
}
dr = dt.NewRow();
dr.ItemArray = rowItems;
dt.Rows.Add(dr);
}
}
private void formatDataGridView()
{
// I noticed that I needed to unregister the event handler to
// prevent DataBindingComplete from firing during the format
dataGridView1.DataBindingComplete -= dataGridView1_DataBindingComplete;
foreach(DataGridViewRow row in dataGridView1.Rows)
{
string originalCell;
string reformattedCell;
if(row.Cells["col1"].Value != null)
{
originalCell = row.Cells["col1"].Value.ToString();
if (originalCell.Count(c => c == '*') == 2)
{
reformattedCell = originalCell.Replace("**", "");
row.Cells["col1"].Value = reformattedCell;
row.Cells["col1"].Style.BackColor = Color.Red;
row.Cells["col1"].ToolTipText = "Divisible by 5";
}
else if (originalCell.Count(c => c == '*') == 1)
{
reformattedCell = originalCell.Replace("*", "");
row.Cells["col1"].Value = reformattedCell;
row.Cells["col1"].Style.BackColor = Color.Red;
row.Cells["col1"].ToolTipText = "Divisible by 7";
}
else
{
//do nothing
}
}
if (row.Cells["col2"].Value != null)
{
originalCell = row.Cells["col2"].Value.ToString();
if (originalCell.Count(c => c == '*') == 2)
{
reformattedCell = originalCell.Replace("**", "");
row.Cells["col2"].Value = reformattedCell;
row.Cells["col2"].Style.BackColor = Color.Red;
row.Cells["col2"].ToolTipText = "Divisible by 5";
}
if (originalCell.Count(c => c == '*') == 1)
{
reformattedCell = originalCell.Replace("*", "");
row.Cells["col2"].Value = reformattedCell;
row.Cells["col2"].Style.BackColor = Color.Red;
row.Cells["col2"].ToolTipText = "Divisible by 7";
}
else
{
//do nothing
}
}
if (row.Cells["col3"].Value != null)
{
originalCell = row.Cells["col3"].Value.ToString();
if (originalCell.Count(c => c == '*') == 2)
{
reformattedCell = originalCell.Replace("**", "");
row.Cells["col3"].Value = reformattedCell;
row.Cells["col3"].Style.BackColor = Color.Red;
row.Cells["col3"].ToolTipText = "Divisible by 5";
}
else if (originalCell.Count(c => c == '*') == 1)
{
reformattedCell = originalCell.Replace("*", "");
row.Cells["col3"].Value = reformattedCell;
row.Cells["col3"].Style.BackColor = Color.Red;
row.Cells["col3"].ToolTipText = "Divisible by 7";
}
else
{
//do nothing
}
}
if (row.Cells["col4"].Value != null)
{
originalCell = row.Cells["col4"].Value.ToString();
if (originalCell.Count(c => c == '*') == 2)
{
reformattedCell = originalCell.Replace("**", "");
row.Cells["col4"].Value = reformattedCell;
row.Cells["col4"].Style.BackColor = Color.Red;
row.Cells["col4"].ToolTipText = "Divisible by 5";
}
else if (originalCell.Count(c => c == '*') == 1)
{
reformattedCell = originalCell.Replace("*", "");
row.Cells["col4"].Value = reformattedCell;
row.Cells["col4"].Style.BackColor = Color.Red;
row.Cells["col4"].ToolTipText = "Divisible by 7";
}
else
{
//do nothing
}
}
}
// Reregistering the event handler
dataGridView1.DataBindingComplete += dataGridView1_DataBindingComplete;
isFormatted = true;
methodCalls++;
MessageBox.Show("Method Calls: " + methodCalls);
}
}
I am not sure how to get around this problem but there has to be a way. I am unfamiliar with DataBindingComplete until recently so I am sure to learn something here. Thanks for the help everyone and helping me learn something new!
CellFormatting event handler was the route I ended up taking to resolve my issue.
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
string originalCell;
string reformattedCell;
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "col1")
{
if(e.Value != null)
{
DataGridViewCell cell =
this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
originalCell = e.Value.ToString();
if (originalCell.Count(c => c == '*') == 2)
{
reformattedCell = originalCell.Replace("**", "");
cell.Value = reformattedCell;
cell.Style.BackColor = Color.Red;
cell.ToolTipText = "Divisible by 5";
}
else if (originalCell.Count(c => c == '*') == 1)
{
reformattedCell = originalCell.Replace("*", "");
cell.Value = reformattedCell;
cell.Style.BackColor = Color.Red;
cell.ToolTipText = "Divisible by 7";
}
else
{
//do nothing
}
}
}
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "col2")
{
if (e.Value != null)
{
DataGridViewCell cell =
this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
originalCell = e.Value.ToString();
if (originalCell.Count(c => c == '*') == 2)
{
reformattedCell = originalCell.Replace("**", "");
cell.Value = reformattedCell;
cell.Style.BackColor = Color.Red;
cell.ToolTipText = "Divisible by 5";
}
else if (originalCell.Count(c => c == '*') == 1)
{
reformattedCell = originalCell.Replace("*", "");
cell.Value = reformattedCell;
cell.Style.BackColor = Color.Red;
cell.ToolTipText = "Divisible by 7";
}
else
{
//do nothing
}
}
}
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "col3")
{
if (e.Value != null)
{
DataGridViewCell cell =
this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
originalCell = e.Value.ToString();
if (originalCell.Count(c => c == '*') == 2)
{
reformattedCell = originalCell.Replace("**", "");
cell.Value = reformattedCell;
cell.Style.BackColor = Color.Red;
cell.ToolTipText = "Divisible by 5";
}
else if (originalCell.Count(c => c == '*') == 1)
{
reformattedCell = originalCell.Replace("*", "");
cell.Value = reformattedCell;
cell.Style.BackColor = Color.Red;
cell.ToolTipText = "Divisible by 7";
}
else
{
//do nothing
}
}
}
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "col4")
{
if (e.Value != null)
{
DataGridViewCell cell =
this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
originalCell = e.Value.ToString();
if (originalCell.Count(c => c == '*') == 2)
{
reformattedCell = originalCell.Replace("**", "");
cell.Value = reformattedCell;
cell.Style.BackColor = Color.Red;
cell.ToolTipText = "Divisible by 5";
}
else if (originalCell.Count(c => c == '*') == 1)
{
reformattedCell = originalCell.Replace("*", "");
cell.Value = reformattedCell;
cell.Style.BackColor = Color.Red;
cell.ToolTipText = "Divisible by 7";
}
else
{
//do nothing
}
}
}
}
You need to change:
the formatting in the DataBindingComplete event, but not the value
supply a "clean" value to display in the CellFormatting Event (e.Value) which does not change the underlying value stored in the dataviewgrid cell, just what value is passed to the painting event to show on the screen
Remember that when going through the data to set the formating, for efficiency if the types of CellStyles are limited e.g Good Result, Bad Result (my code has actually about 11 default styles) create the styles first.
Then assign them as you check you cell values and work out which style to use.
The only caveat of this is that later on if you change e.g Column = 12, Row = 4 cellstyle in some way it will affect all cells "sharing" the same default DataGridViewCellstyle.
e.g
Font bFont = new Font("Calibri", defFontSize, FontStyle.Bold); // Bold font
Font iFont = new Font("Calibri", defFontSize, FontStyle.Italic); // Italic font
Font nFont = new Font("Calibri", defFontSize); // Normal font
DataGridViewCellStyle dgvcsOKRESULT = new DataGridViewCellStyle()
{
Font = nFont,
ForeColor = Color.White,
BackColor = Color.Green,
};
DataGridViewCellStyle dgvcsBADRESULT = new DataGridViewCellStyle()
{
Font = bFont,
ForeColor = Color.White,
BackColor = Color.Red,
};
Call formatDataGridView from the bindData method and forget about the DataBinding event:
private void bindData()
{
dataGridView1.DataSource = dt;
formatDataGridView();
}
Or is there a reason this is not possible?

Categories