R
R
RommB2021-03-28 23:00:11
C++ / C#
RommB, 2021-03-28 23:00:11

How to highlight with color those elements of the first matrix that are larger than the corresponding elements of the second matrix in c#?

Good evening, I work with windows forms (beginner in this business) and I had such a problem, a person opens his two matrices and when you click on the task button, the elements of the first matrix should be highlighted, which are larger than the corresponding elements of the second matrix. How to do it ?

Here is my code:

private void task1_Click(object sender, EventArgs e)
        {
            int n1, n2;
            for (int j = 0; j < dataGridView1.ColumnCount; j++)
            {
                var needToSelect = true;
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    if (int.TryParse(dataGridView1[j, i].Value.ToString(), out n1) && int.TryParse(dataGridView2[j, i].Value.ToString(), out n2))
                    {
                        if (n1 > n2)
                            needToSelect = false;
                            break;
                    }                 
                }
                if (needToSelect)
                {
                    dataGridView1.Columns[j].DefaultCellStyle.BackColor = Color.Chartreuse;
                }
                else
                {
                    dataGridView1.Columns[j].DefaultCellStyle.BackColor = Color.White;
                }
                task2.Enabled = true;
            }
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Foggy Finder, 2021-03-28
@FoggyFinder

You need to apply the style not to the entire column, but to each cell individually.
Just replace

dataGridView1.Columns[j].DefaultCellStyle.BackColor = Color.Chartreuse;

on the
dataGridView1[j, i].Style.BackColor = Color.Chartreuse;

for the else branch - similarly.
For the rest:
* Look at the boundaries of the cycles, both times use the number of columns - the boundaries for the second should be determined by the number of rows
Updated (typo fixed)
Should be something like this
private void task1_Click(object sender, EventArgs e)
{
    int n1, n2;
    for (int j = 0; j < dataGridView1.ColumnCount; j++)
    {
        for (int i = 0; i < dataGridView1.RowCount; i++)
        {
            if (int.TryParse(dataGridView1[j, i].Value.ToString(), out n1) 
                && int.TryParse(dataGridView2[j, i].Value.ToString(), out n2))
            {
                if (n1 > n2)
                {
                    dataGridView1[j, i].Style.BackColor = Color.Chartreuse;
                }
                else
                {
                    dataGridView1[j, i].Style.BackColor = Color.White;
                }
            }
        }
    }

    task2.Enabled = true;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question