Home > Blockchain >  Periods time schedule in DataGridView in c#
Periods time schedule in DataGridView in c#

Time:11-24

I have DataGridView called TimesDgv has contain school periods times. I want automatically generate times. Like this Screenshot image. How can I do this?

This is my code

 for (int i = 0; i < TimesDgv.RowCount - 1; i  )
            {
                TimesDgv.Rows[i].Cells[1].Value = TimesDgv.Rows[i].Cells[2].Value;
                DateTime time = Convert.ToDateTime(TimesDgv.Rows[i].Cells[1].Value);
                TimesDgv.Rows[i].Cells[2].Value = time.AddMinutes(40).ToString("hh:mm");
            }

enter image description here

enter image description here

CodePudding user response:

Try the code below that takes the initial starting time value from the combo box, then combines that to today’s date to create a DateTime object. Then a simple loop through the grids rows sets the time values based on the “periodName.” If the period name is “rest” then it adds 5 minutes to the date time and if the period name is not “rest”, then the code adds 40 minutes to the DateTime.

private void button1_Click(object sender, EventArgs e) {
  string dt = DateTime.Now.ToShortDateString()   " "   comboBox1.Text;
  if (DateTime.TryParse(dt, out DateTime currentTime)) {
    for (int i = 0; i < TimesDgv.RowCount; i  ) {
      if (!TimesDgv.Rows[i].IsNewRow) {
        if (TimesDgv.Rows[i].Cells[0].Value != null && !string.IsNullOrEmpty(TimesDgv.Rows[i].Cells[0].Value.ToString())) {
          TimesDgv.Rows[i].Cells[1].Value = currentTime;
          if (TimesDgv.Rows[i].Cells[0].Value.ToString() == "rest") {
            currentTime = currentTime.AddMinutes(5);
          }
          else {
            currentTime = currentTime.AddMinutes(40);
          }
          TimesDgv.Rows[i].Cells[2].Value = currentTime;
        }
      }
    }
  }
  else {
    MessageBox.Show("Invalid time in combo box");
  }
}
  • Related