Previous question: https://learn.microsoft.com/en-us/answers/questions/1658584/calendar-booking-using-datagridview
View_CellPainting method from my answer can be used as is by defining it as follows:
public partial class Form1 : Form
{
private DataGridView view { get => dataGridView1; }
private DataGridViewColumn startTimeColumn { get => view.Columns[2]; }
private DataGridViewColumn endTimeColumn { get => view.Columns[3]; }
public int gridYear { get => monthCalendar1.SelectionStart.Year; }
public int gridMonth { get => monthCalendar1.SelectionStart.Month; }
private readonly Brush brush = new SolidBrush(Color.Blue);
const int offset = 4;
public Form1() {
InitializeComponent();
view.CellPainting += View_CellPainting;
}
private void View_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
if (e.RowIndex < 0 || e.ColumnIndex <= endTimeColumn.Index) return;
if (view.Rows[e.RowIndex].IsNewRow) return;
object startValue = view[startTimeColumn.Index, e.RowIndex].Value;
object endValue = view[endTimeColumn.Index, e.RowIndex].Value;
if (!(startValue is DateTime) || !(endValue is DateTime)) return;
DateTime startTime = (DateTime)startValue;
DateTime endTime = (DateTime)endValue;
int day = int.Parse(view.Columns[e.ColumnIndex].HeaderText);
DateTime dayStart = new DateTime(gridYear, gridMonth, day);
DateTime dayEnd = dayStart.AddDays(1);
TimeSpan daySpan = dayEnd - dayStart;
if (startTime < dayEnd && endTime >= dayStart) {
e.Paint(e.CellBounds, DataGridViewPaintParts.All);
int top = e.CellBounds.Top + 4;
int bottom = e.CellBounds.Bottom - 4;
int left = (int)(e.CellBounds.Width * (startTime - dayStart).TotalMinutes / daySpan.TotalMinutes);
if (left < 0) left = 0;
left = e.CellBounds.Left + left;
int right = (int)(e.CellBounds.Width * (dayEnd - endTime).TotalMinutes / daySpan.TotalMinutes);
if (right < 0) right = 0;
right = e.CellBounds.Right - right;
Rectangle face = Rectangle.FromLTRB(left, top, right, bottom);
e.Graphics.FillRectangle(brush, face);
e.Handled = true;
}
}