问题
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