根据条件更改datagridview行颜色

时间:2019-01-25 12:47:45

标签: c# winforms datagridview cell

我已将数据从数据库加载到DatagridView,并且有一些带有“开始”和“结束”日期的汽车预定。因此,加载数据不是问题。我的数据库中的StartDateShortdate是短数据库,我的意思是只有日期而没有时间。 我喜欢跟随它们来加载它们,并且我希望那些与今天相同或比今天更旧的行被涂成红色。我的意思是ForeColore = red。我该怎么办?

DateTime today = DateTime.Now;
var shortDate = today.Date.AddDays(0);

var ReservedCars = (from r in db.Reservation 
                    select new
                    {
                      ReservationID = r.ReservationId,
                      Startdate = r.StartDate,
                      Enddate = r.EndDate 
                    }).ToList();


            dgvReservedRooms.DataSource = ReservedCars; 
            DateTime today = DateTime.Now;
            var shortDate = today.Date.AddDays(0);

// I tried like this but doesn't work with colors, please help...
 foreach (DataGridViewRow row in dgvReservedCars.Rows)
            { 
                foreach (var re in ReservedCars)
                {
                    if (re.Enddate <= shortDate)
                    {
                        row.DefaultCellStyle.BackColor = Color.Red;
                    }
                }
            }

1 个答案:

答案 0 :(得分:0)

我看到了几个可能的问题。首先:您的for语句正在执行着色检查。对于datagridview中的每一行,它将经历每个保留(不只是与该行关联的保留),并且如果其中任何一个的Enddate <=今天,则该行将被设置为红色。因此,如果任何预订今天的结束日期<=,那么所有预订都会变成红色。相反,您需要检查与该行关联的预订是否具有结束日期<=今天。

第二,您需要将行样式更改放在DataBindingComplete的{​​{1}}事件中,而不是放在设置数据源的同一函数中。我认为您遇到的问题已在此处得到解答:https://stackoverflow.com/a/13560694/2263392

因此,通过这两项更改,代码看起来像这样:

DataGridView

public Form1() { InitializeComponent(); DateTime today = DateTime.Now; var shortDate = today.Date.AddDays(0); var ReservedCars = (from r in db.Reservation select new ReservationRow( r.ReservationId, r.StartDate, r.EndDate)).ToList(); dgvReservedCars.DataSource = ReservedCars; } private void dgvReservedCars_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { DateTime today = DateTime.Now; var shortDate = today.Date.AddDays(0); foreach (DataGridViewRow row in dgvReservedCars.Rows) { ReservationRow res = row.DataBoundItem as ReservationRow; if (res.EndDate <= shortDate) { row.DefaultCellStyle.BackColor = Color.Red; } } } 的简单之处是:

ReservationRow