开发者

C# coloring the same values in row of datagridview

开发者 https://www.devze.com 2022-12-15 21:30 出处:网络
Say I have a datagridviewfilled with rows. Now to make certain 开发者_运维知识库data more distinct I\'d like to color the background of certain cells.

Say I have a datagridview filled with rows. Now to make certain 开发者_运维知识库data more distinct I'd like to color the background of certain cells. There's some caveats though, the amount of columns I want coloring in can vary. To make things more clear I'll sketch up a fake datagrid:

Name Thing2 col1 col2 col3
tes   test   1    1     2
t2t   ers    3    3     3
der   zoef   2    3     1

Now, the col1-col3 cells need to be colored, depending on their value. The cells in the first column will always be green (by convention) cells deviating from it will be colored red. So, the first row will have col1 and col2 colored green and col3 red et cetera. Any ideas to how i'd best approach this problem?


I suggest using CellFormating event.

First get object associated with current row using e.RowIndex and then color current cell according to current column (e.ColumnIndex) and your object's properties.

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex >= customerBindingSource.Count)
                return;

            switch (e.ColumnIndex)
            {
                case 3:
                    Customer customer = (Customer)customerBindingSource[e.RowIndex];
                    if (customer.Salary > 1000)
                        e.CellStyle.BackColor = Color.Red;
                    break;
            }
        }


would like to alter @Petr response a little bit. Using this you can have unique colour for the rows, even if you have thousand of rows. for every unique value their is a colour associated with it. just need to pass an int value not ranging above 32 bit.

   private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
            {
                switch (e.ColumnIndex)
                {
                    case 3:
                        Customer customer = (Customer)customerBindingSource[e.RowIndex];
                        e.CellStyle.BackColor = Color.FromArgb(customer.Salary); // set unique color for each value
                        break;
                }            

            }


If after you've added the data into your grid view you could iterate through the rows/columns and program your various checks then just assign a backcolor as appropriate?

foreach(DatGridViewEow row in datagridview1.Rows)
{
     for(int i=3;i<5;i++)
     {
          DataGridViewCell cell = row.cells[i];
          cell.style.backcolor = Color.Red;
     }
}

Don't know if that would work if the data was from a datasource though.


All the suggestions have helped me come to the following solution, though Petr will get the V, since he was the first to learn me about using the cellformatting event.

    /// <summary>
    /// Applies coloring to the result rows in the dataGrid
    /// </summary>
    private void ApplyColoring()
    {   
        if (dataGridView1.DataSource != null)
        {   
            // hardmap a color to a column
            IDictionary<Int32, Color> colorDictionary = new Dictionary<Int32, Color>();
            colorDictionary.Add(6, Color.FromArgb(194, 235, 211));
            colorDictionary.Add(7, Color.Salmon);
            colorDictionary.Add(8, Color.LightBlue);
            colorDictionary.Add(9, Color.LightYellow);
            colorDictionary.Add(10, Color.LightGreen);
            colorDictionary.Add(11, Color.LightCoral);
            colorDictionary.Add(12, Color.Blue);
            colorDictionary.Add(13, Color.Yellow);
            colorDictionary.Add(14, Color.Green);
            colorDictionary.Add(15, Color.White);

            IList<String> checkedValues = new List<String>();

            // first we loop through all the rows
            foreach (DataGridViewRow gridRow in dataGridView1.Rows)
            {
                IDictionary<String, Int32> checkedVal = new Dictionary<String, Int32>();

                // then we loop through all the data columns
                int maxCol = dnsList.Count + 6;
                for (int columnLoop = 6; columnLoop < maxCol; columnLoop++)
                {
                    gridRow.Cells[columnLoop].Style.BackColor = Color.FromArgb(194, 235, 211);
                    string current = gridRow.Cells[columnLoop].Value.ToString();

                    for (int checkLoop = 6; checkLoop < maxCol; checkLoop++)
                    {
                        string check = gridRow.Cells[checkLoop].Value.ToString();

                        if (!current.Equals(check))
                        {
                            if (checkedVal.Keys.Contains(current))
                            {
                                gridRow.Cells[columnLoop].Style.BackColor = colorDictionary[checkedVal[current]];
                            }
                            else
                            {
                                gridRow.Cells[columnLoop].Style.BackColor = colorDictionary[columnLoop];
                                checkedVal.Add(current, columnLoop);
                            }
                        }
                    }
                }
            }
        }
    }

EDIT: january 20th, the dictionary with colors maps to the (possible) columns that can be colored. In the case of my application we will never ever get more then 10 columns, but you can easily make them start over by using a MOD operation or w/e.

0

精彩评论

暂无评论...
验证码 换一张
取 消