将数据从数据库添加到dataGridView - C#/ SQL Server(Staff Rota)

时间:2018-04-07 12:42:51

标签: c# .net sql-server datagridview

示例数据:

Id | Name       |   DOB     | TEL         | Address        | WDays   | DateInWork
---+------------+-----------+-------------+----------------+---------+---------------
 2 | Conall B   |1999-10-20 | 07654227534 | 1 Made up Road | Sun-Wed | 2020-04-12
 2 | Conall B   |1999-10-20 | 07654227534 | 1 Made up Road | Sun-Wed | 2020-05-11
 3 | Michael J  |1999-10-19 | 07755428737 | 15 Made up St  | Sun-Wed | 2020-04-12
 4 | Kuba R     |1992-04-11 | 07654421231 | 7 Made up Aven | Sun-Wed | 2020-04-12
 8 | Connor T   |1994-07-23 | 07628395102 | 9 Made up Garde| Sun-Wed | 2020-04-12
11 | Harry G    |1997-12-31 | 07676192327 |19 Made up St   | Sun-Wed | 2020-04-12

执行此命令时返回此数据:

SELECT 
    s.*, b.DateOfEvent 
FROM 
    Staff s, Booking b, BookingStaff bs 
WHERE 
    bs.StaffId = s.StaffId 
    AND bs.BookingId = b.BookingId  
    AND b.DateOfEvent BETWEEN '01/01/2018' AND '12/12/2020'

如您所见,涉及3个表格。预订表,员工表和BookingStaff表。预订与BookingStaff有1-M的关系,工作人员还有1-M的BookingStaff。 好吧,在UI上,我希望将这些数据从当前状态调整 - 如示例数据部分所示,更加用户友好状态。基本上,datagridview将包含从星期一到星期日的列。行标题值将是Staffid / Name / Age。 到目前为止,我的代码如下:

SqlCommand Staff = new SqlCommand("SELECT s.*, b.DateOfEvent FROM Staff s, Booking b, BookingStaff bs WHERE bs.StaffId = s.StaffId AND bs.BookingId = b.BookingId AND b.DateOfEvent BETWEEN '" + Convert.ToDateTime(startDate) + "' AND '" + Convert.ToDateTime(endDate) + "'", c);

        c.Open();
        List<string> staffids = new List<string>();
        using(SqlDataReader reader = Staff.ExecuteReader())
        {
            while(reader.Read())
            {
                string staffId = Convert.ToString(reader["StaffId"]);

                string Name = Convert.ToString(reader["FirstName"]) +" " + Convert.ToString(reader["Surname"]);
                DateTime DOB = Convert.ToDateTime(reader["DOB"]);
                string Age = Convert.ToString(((DateTime.Today.Year * 100 + DateTime.Today.Month) * 100 + DateTime.Today.Day) - ((DOB.Year * 100 + DOB.Month) * 100 + DOB.Day));
                string DaysInWork = Convert.ToDateTime(reader["DateOfEvent"]).Day.ToString();
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if(!staffids.Contains(staffId))
                    {
                        row.HeaderCell.Value = "Staff ID: " + staffId + "\n" + "Name:" + Name + "\n" + "Age:" + Age; 
                    }

                }
                staffids.Add(staffId);
            }
        }
        c.Close();

我遇到的当前问题是将数据插入正确的位置。好的说我星期一有5人分配到预订。然后星期一的5个单元格将填满。但是后来说这5个中的1个也适用于那周的星期二如何将这些数据插入星期二?任何帮助,将不胜感激。我很抱歉,如果这个,根本没有得到很好的解释。这是我想要的形象:https://rotacloud-website.s3.amazonaws.com/v2/img/pages/home/product-ss.png

0 个答案:

没有答案