Change Row Color in Datagridview based on values of a cells in another Datagridview

孤街浪徒 提交于 2019-12-12 04:44:23

问题


I'm using c# winform sql server

In my database I try to manage the employee vacations in my small company so I was created two tables

first table called tblMember

idMember (PK, int, not null)

memberName (varchar(50), null)

that table related in one to many relationship to

second table called tblVacations

idVacation (PK, int, not null)

vacationStart (date, null)

vacationEnd (date, null)

idMember_L(FK, int, null)

then I created a form with two datagridview the first called dg_member populate its data (names from tblMember) throw a stored procedure

the second datagridview dgVacation populate the related data

now I want to colored with red the name in dg_member who absent today ( today is fall between vacationStart and vacationEnd ) and if the member is coming today ( today equal vacationEnd ) the name turn to green

i tried the code :

private void dgMember_Grade_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            foreach (DataGridViewRow Myrow in dgMember_Grade.Rows)
            {
                var cvStart = dgVacation.Rows[0].Cells[1].Value;
                var cvEnd = dgVacation.Rows[0].Cells[2].Value;

                if (cvStart == null || cvStart == DBNull.Value)
                    continue;

                DateTime startDate = Convert.ToDateTime(cvStart);
                DateTime endDate = Convert.ToDateTime(cvEnd);

                if (startDate < DateTime.Now && endDate > DateTime.Now)
                {
                    Myrow.DefaultCellStyle.BackColor = Color.Red;
                }
                else if (endDate == DateTime.Now)
                {
                    Myrow.DefaultCellStyle.BackColor = Color.Green;
                }
            }
        }

but it gives me an error

Index was out of range. Must be non-negative and less than the size of the collection.

thank you


回答1:


declare @tmw Date  = DATEADD(day, 1,getdate())
select


m.MemberName
, case when t.idMember_L is null then 'False' else 'True' end as OnHoliday
, case when (select count (tm.idMember_L) from tblVacations tm where
    m.idMember = tm.idMember_L and
     t.vacationStart <= @tmw and t.vacationEnd >= @tmw ) > 0
     then 'False' else 'True' end as OnHolidayTomorrow
 from tblMember m
     left outer join tblVacations t
     on m.idMember = t.idMember_L and
     t.vacationStart <= getdate() and t.vacationEnd >= getdate()


来源:https://stackoverflow.com/questions/33146271/change-row-color-in-datagridview-based-on-values-of-a-cells-in-another-datagridv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!