I want to highlight non-numeric value by a color by clicking a button in C#. I have tried below code to get output, however I got no success.
Can anyone help me with this?
private void Stnineteen_Click(object sender, EventArgs e)
{
for (int i = DataGridView1.RowCount - 2; i >= 0; i--)
{
for (int j = 0; j < DataGridView1.RowCount - 0; j++)
{
string grid1 = DataGridView1.Rows[i].Cells[10].Value.ToString();
if (grid1 =="")
{
DataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
//break;
}
else if(grid1 == "0")
{
DataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
//break;
}
else
{
DataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Green;
}
}
}
Something like this should work:
double d;
foreach(DataGridViewRow r in DataGridView1.Rows)
{
if (r.IsNewRow) return; //we don't want to do anything to the edit row.
if (r.Cells[1].Value == null || r.Cells[10].Value.ToString() == "0")
{
r.Cells[1].Style.BackColor = Color.Red;
}
else if(double.TryParse(r.Cells[10].Value.ToString(), out d)) //if it can be parsed to a number
{
r.Cells[1].Style.BackColor = Color.Green;
}
else
{
//Cannot be parsed to a number
r.Cells[10].Style.BackColor = Color.Yellow;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.