开发者

Datagridview cell color change doesnt work

开发者 https://www.devze.com 2023-01-06 16:02 出处:网络
I Have a Datagridview bound to a datatable wich hold data from a database I made a function that checked if a date is within a correct time range开发者_运维知识库

I Have a Datagridview bound to a datatable wich hold data from a database

I made a function that checked if a date is within a correct time range开发者_运维知识库

if its correct nothing happens.

else it has to change the color of the row/cell to red

I tried a lot of things but nothing works

Here is the method i created:


        private void CheckFactTermijn()
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                DateTime FactuurDatum = Convert.ToDateTime(dataGridView1.Rows[i].Cells[2].Value.ToString());
                int termijn = Convert.ToInt32(dataGridView1.Rows[i].Cells[7].Value.ToString());
                DateTime finalDate = FactuurDatum.AddDays((double)termijn);

if (finalDate > DateTime.Now) { } else { dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red; } } }


I believe the solution lies in WHEN you set the color, not the method in which you do so. Several different events have been suggested and some will indeed work. One of the problems with using either the cellformatting, databindingcomplete, or even paint events is that they get fired multiple times. From what I've gathered, there is an issue with the datagridview control in that you cannot change the color of any of the cells until AFTER the form has been shown. Thus methods that run, or events that fire before Shown() is called will not change the color. The events that are sited as the solution to the problem usually work, but since they're called many times, may not be the most efficient answer.

Probably the simplest solution to the issue is to put your code to fill/color your grids in the Shown() method of your form instead of the constructor. Below is a link to a post in the msdn forums that tipped me off to the solution, it's marked as the answer about 3/4 of the way down the page.

MSDN forums post with the Solution


I'm not sure when your code is running, but try setting your DataGridView's DefaultCellStyle properties in your DGV's DataGridView.CellFormatting Event.

The MSDN link above has an example of what you're trying to do.

Note that you won't be iterating through each row in your DGV (like your method does); you'd instead use the DataGridViewCellFormattingEventArgs ColumnIndex property to check which column the event fired for.


dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;

Must change the bakColor for entire row. Except for cells having own Style.BackColor set.

You can set a breakPoint at sentence to verify it does.

0

精彩评论

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