HypernovaDesktop Components · docs
Binarymission
WinForms › Project Management › GanttChart

GanttChart

class.NET 6 / 8 / 10.NET Framework 4.8Binarymission.WinForms.Controls.ProjectManagement

A Gantt chart for Windows Forms: a task list beside a timeline of bars, summary brackets, milestones and dependency arrows, scheduled by the critical-path method and edited with the mouse or entirely from the keyboard.

public partial class GanttChart : Control

Inherits from / implements: Control

Remarks

What it is for

Use it wherever people plan work against dates: a project plan, a release schedule, a production run, a fit-out programme. The task list on the left is a tree grid – outline number, name, dates, length, progress, assignee and predecessors – and the timeline on the right shows each task as a bar on the calendar, with weekends and holidays shaded, a line at today and the critical path picked out in its own colour. A splitter between the two moves the boundary.

The plan

Give the chart a list of ProjectTask objects in Tasks and the dependencies between them as TaskLink objects in Links. A task becomes a summary when other tasks name it as their ProjectTask.ParentId, and a milestone when its duration is zero. The chart never keeps dates of its own: it schedules the plan on the working calendar of ProjectStart, WorkingWeek and Holidays (see ProjectScheduler) and draws the result, which Schedule returns. Data that cannot be used – a duplicate id, a link to a missing task, a loop – is reported in ProjectSchedule.Problems, and everything else is still drawn.

Use an ObservableCollection or a BindingList for the two lists and the chart watches them and every object in them: add a task, change a duration, and the chart schedules again and redraws. Give the same two collections to a PertChart and a TaskBoard and all three show one plan; an edit made in any of them is seen by the others at once.

Editing

A reader can drag a bar to move it, drag its end to change its length, drag the small triangle under it to record progress, and drag from the dot at its end to another bar to link the two. A slow second click on a cell, or F2, edits it: the name, the start, the length, the progress, or the predecessors, typed as a planner writes them (2, 3SS+1). Every edit is offered first through the cancelable TaskChanging or LinksChanging event, then written to the task or link objects themselves, then announced by TaskChanged or LinksChanged – so an application enforces its own rules in one handler, whichever way the edit was made. ReadOnly turns editing off.

Keyboard

KeysAction

Up, Down, Home, End, Page Up, Page Down

Move between rows.

Left, Right

Move between the editable cells of the row; at the name, close and open a summary or go to its parent.

Shift+Left, Shift+Right

Move the selected task a working day earlier or later.

Ctrl+Shift+Left, Ctrl+Shift+Right

Shorten or lengthen the selected task by a working day.

Ctrl+Left, Ctrl+Right

Scroll the timeline.

Plus, Minus

Open and close the selected summary.

Ctrl+Plus, Ctrl+Minus

Zoom in and out.

F2

Edit the current cell; Enter commits, Tab moves to the next editable cell, Esc cancels.

Enter, Space

Raise TaskActivated for the selected task.

Delete

Remove the selected link.

Esc

Cancel a drag in progress.

The wheel scrolls the rows, with Shift scrolls sideways, and with Ctrl zooms about the date under the pointer. Each row is exposed to screen readers as an outline item that says the task's dates, length, progress and whether it is critical.

Appearance

The bars, the critical path, summaries, baselines and the today line each have a colour of their own (BarColor, CriticalBarColor and so on). The grid lines, weekend shading, links and headers default to shades worked out from Control.ForeColor and BackColor, so setting those two for a dark theme gives a dark chart. In Windows high-contrast mode the system colours are used instead. The timeline's scale is Zoom; every size is in logical pixels (1/96 inch) and scales with the display. ExportImage and CreatePrintDocument draw the whole plan as an image or across printed pages.

Examples

A form showing an eight-task website plan, with the assignee and progress columns added, a rule that finished work cannot be moved, and the finish date in the title bar. On a Monday-to-Friday week from 2 November 2026 the plan finishes on 1 December 2026, and the critical path runs through the brief, the wireframes, the front end, testing and go-live.

using System;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Windows.Forms;
using Binarymission.WinForms.Controls.ProjectManagement;

public sealed class PlanForm : Form
{
    private readonly GanttChart _gantt = new GanttChart();
    private readonly ObservableCollection<ProjectTask> _tasks = new ObservableCollection<ProjectTask>();
    private readonly ObservableCollection<TaskLink> _links = new ObservableCollection<TaskLink>();

    public PlanForm()
    {
        Text = "Website relaunch";
        Size = new Size(1100, 520);

        _tasks.Add(new ProjectTask("design", "Design"));
        _tasks.Add(new ProjectTask("brief", "Agree the brief", 3) { ParentId = "design", Assignee = "Priya", Progress = 100 });
        _tasks.Add(new ProjectTask("wire", "Wireframes", 5) { ParentId = "design", Assignee = "Priya", Progress = 40 });
        _tasks.Add(new ProjectTask("build", "Build"));
        _tasks.Add(new ProjectTask("front", "Front end", 10) { ParentId = "build", Assignee = "Tom" });
        _tasks.Add(new ProjectTask("api", "Order API", 8) { ParentId = "build", Assignee = "Aisha" });
        _tasks.Add(new ProjectTask("test", "User testing", 4) { Assignee = "Priya" });
        _tasks.Add(new ProjectTask("live", "Go live", 0));

        _links.Add(new TaskLink("brief", "wire"));
        _links.Add(new TaskLink("wire", "front"));
        _links.Add(new TaskLink("wire", "api", TaskLinkType.StartToStart, 2));
        _links.Add(new TaskLink("build", "test"));
        _links.Add(new TaskLink("test", "live"));

        _gantt.Dock = DockStyle.Fill;
        _gantt.Tasks = _tasks;
        _gantt.Links = _links;
        _gantt.ProjectStart = new DateTime(2026, 11, 2);
        _gantt.Holidays.Add(new DateTime(2026, 12, 25));
        _gantt.Columns = GanttColumns.Default | GanttColumns.Assignee | GanttColumns.Progress;
        _gantt.TaskChanging += OnTaskChanging;
        _gantt.ScheduleChanged += (sender, e) => ShowFinish();
        Controls.Add(_gantt);

        Load += (sender, e) =>
        {
            ShowFinish();
            _gantt.ZoomToFit();
        };
    }

    private void OnTaskChanging(object sender, TaskChangingEventArgs e)
    {
        // Finished work stays where it is; its name can still be corrected.
        if (e.Task.Progress >= 100 && (e.NewStart.HasValue || e.NewDuration.HasValue))
            e.Cancel = true;
    }

    private void ShowFinish()
    {
        Text = "Website relaunch - finishes " + _gantt.Schedule.ProjectFinish.ToString("d MMM yyyy");
    }
}

See also

Members at a glance

Constructors
GanttChartCreates a Gantt chart with an empty plan: empty, watched Tasks, Links and Holidays collections, a Monday-to-Friday week, and the timeline at GanttZoom.Week.
Properties
BackColorGets or sets the background of both panes, behind the rows and the timeline.
BarColorGets or sets the colour of a task bar: its finished part and its outline are drawn in it, and the rest of the bar in a lighter tint of it.
BaselineColorGets or sets the colour of the thin baseline bar drawn under a task's bar.
ColumnsGets or sets which columns the task list shows beside the task's name.
CriticalBarColorGets or sets the colour of the tasks and links on the critical path – the ones that cannot slip without moving the finish.
GridLineColorGets or sets the colour of the lines between rows and columns, in the task list and on the timeline.
GridWidthGets or sets the width of the task list, the left-hand pane.
HeaderBackColorGets or sets the background of the column headings and the two rows of dates over the timeline.
HolidaysGets or sets the dates that are not worked, such as public holidays and a Christmas shutdown.
LinkColorGets or sets the colour of the link arrows that are not on the critical path.
LinksGets or sets the dependencies between the tasks.
NonWorkingDayColorGets or sets the shading behind weekends, holidays and any other day the plan does not work.
ProjectStartGets or sets the first day work can happen. No task is scheduled before it, except one that must start on an earlier date.
ReadOnlyGets or sets whether the reader is stopped from changing the plan.
RowHeightGets or sets the height of a row, in the task list and on the timeline alike.
SelectedTaskGets or sets the task whose row is selected.
ShowBaselinesGets or sets whether each task's baseline – the dates originally agreed for it – is drawn as a thin bar under its current bar, so slippage shows at a glance.
ShowCriticalPathGets or sets whether the tasks and links on the critical path – the ones that cannot slip without moving the finish – are drawn in CriticalBarColor.
ShowLinksGets or sets whether the links between tasks are drawn as arrows on the timeline.
ShowTodayGets or sets whether a line is drawn down the timeline at today's date, in TodayColor.
SummaryBarColorGets or sets the colour of a summary task's bracket and of a milestone's diamond.
TasksGets or sets the tasks of the plan, in outline order within each parent.
TodayGets or sets the date the today line is drawn at.
TodayColorGets or sets the colour of the line drawn down the timeline at today's date.
WeekStartGets or sets the day each week starts on in the timeline's headings.
WorkingWeekGets or sets the days of the week that are worked. Durations and lags count only these days, and the timeline shades the others.
ZoomGets or sets how much time the timeline shows, from a column per day to a column per half-year.
Methods
CollapseAllCloses every summary task, leaving only the top-level rows. TaskToggled is raised for each summary that was open.
CreateAccessibilityInstanceCreates the accessible object that presents the chart to screen readers and other assistive technology as an outline: one item per visible row, each saying the task's name, dates, length, progress and whether it is critical.
CreatePrintDocumentCreates a document that prints the whole chart, with every task shown and every summary open.
DisposeStops watching the plan and releases the fonts, the tooltip and the timer the chart created. The scroll bars and the cell editor are child controls and are released with the chart.
EnsureScheduleGets the plan as the chart has scheduled it: every task's dates and float, the links that were honoured, the critical path, the project's start and finish, and anything in the plan that could not be used.
ExpandAllOpens every summary task, so every task has a row. TaskToggled is raised for each summary that was closed.
ExportImageDraws the whole chart into a new image: the task list and the timeline side by side, with every task shown and every summary open, across the plan's whole span.
IsExpandedTells whether a summary task's subtasks are shown.
IsInputKeyClaims the keys the chart uses for itself, so that the form does not take them for moving the focus or pressing a button.
OnBackColorChangedRaises Control.BackColorChanged and redraws with the new background, and the colours worked out from it.
OnDpiChangedAfterParentLays the chart out again when it moves to a display with a different scale, so that every logical size is converted at the new DPI and the fonts are rebuilt.
OnFontChangedRebuilds the bold font summaries are written in and lays the chart out again for the new font, then raises Control.FontChanged.
OnForeColorChangedRaises Control.ForeColorChanged and redraws with the new text colour, and the colours worked out from it.
OnGotFocusRedraws the selection in its focused colour and announces it to screen readers. Tabbing into a chart with nothing selected selects the first row, so the keyboard has somewhere to start.
OnHandleCreatedRaises any schedule and selection events that were held back until the chart had a window.
OnHandleDestroyedForgets notifications posted to a window that is going away; the next window posts them again.
OnKeyDownRaises Control.KeyDown, then carries out the chart's keyboard commands – moving between rows and cells, moving and stretching tasks, zooming, editing – unless a handler has already handled the key. The keys are listed in the remarks on GanttChart.
OnLinksChangedRaises the LinksChanged event.
OnLinksChangingRaises the LinksChanging event.
OnLostFocusRedraws the selection in its unfocused colour.
OnMouseCaptureChangedAbandons a drag without applying it when the mouse is taken away part way through – by a dialog opening or the window losing activation – as Esc does.
OnMouseDoubleClickRaises Control.MouseDoubleClick, then raises TaskActivated when the double-click was on a task's row in the task list or on its bar.
OnMouseDownRaises Control.MouseDown, then acts on the press: selects the row under it, opens or closes a summary at its expander, or begins dragging the splitter, a bar, a bar's end, its progress, a new link, or the timeline itself. A right-click selects the row, so a context menu acts on what was clicked.
OnMouseLeaveRaises Control.MouseLeave and clears the hover highlight, unless a drag is in progress.
OnMouseMoveRaises Control.MouseMove, then moves a drag in progress, or updates the hover highlight, the pointer shape and the tooltip for what is under the pointer.
OnMouseUpRaises Control.MouseUp, then finishes a drag: a bar moved or stretched, progress or a link is offered through TaskChanging or LinksChanging.
OnMouseWheelRaises Control.MouseWheel, then scrolls the rows by the system's lines per notch; with Shift, scrolls sideways the pane under the pointer; with Ctrl, zooms one step per notch about the date under the pointer.
OnPaintDraws the task list, the splitter, the timeline and the headers, then raises Control.Paint. A fault while drawing is absorbed rather than leaving the control crossed out, and the next paint tries again.
OnResizeRaises Control.Resize and lays the panes and scroll bars out for the new size.
OnScheduleChangedRaises the ScheduleChanged event.
OnSelectedTaskChangedRaises the SelectedTaskChanged event.
OnTaskActivatedRaises the TaskActivated event.
OnTaskChangedRaises the TaskChanged event.
OnTaskChangingRaises the TaskChanging event.
OnTaskToggledRaises the TaskToggled event.
OnZoomChangedRaises the ZoomChanged event.
RescheduleSchedules the plan again now, redraws, and raises ScheduleChanged.
ResetBackColorReturns BackColor to its default, SystemColors.Window. The Properties window's Reset command calls this.
ScrollToTaskScrolls a task's row and bar into view, opening the summaries it is in.
ScrollToTodayScrolls the timeline so that today's date – Today, or the computer's date – is a third of the way across it.
SetExpandedOpens or closes a summary task.
SizeGets the size the chart is given when it is first placed on a form: room for the task list and a few weeks of timeline.
ZoomInShows less time in more detail: one GanttZoom step finer, keeping the date in the middle of the timeline where it is. Does nothing at GanttZoom.Day.
ZoomOutShows more time in less detail: one GanttZoom step coarser, keeping the date in the middle of the timeline where it is. Does nothing at GanttZoom.Year.
ZoomToFitPicks the finest zoom at which the whole plan fits across the timeline without scrolling sideways, and scrolls to the plan's start.
Events
LinksChangedOccurs after links the reader added or removed have been written to Links.
LinksChangingOccurs before the reader adds or removes links – a link drawn between two bars, a predecessor list typed into a cell, or a selected link deleted – so that the application can refuse the change.
ScheduleChangedOccurs after the plan has been scheduled again because something in it changed: a task, a link, a collection, a holiday, ProjectStart or WorkingWeek.
SelectedTaskChangedOccurs when SelectedTask changes, by the reader, by the application, or because the selected task left the plan.
TaskActivatedOccurs when the reader double-clicks a task's row or bar, or presses Enter or Space with its row selected: the moment to open the application's own view of the task.
TaskChangedOccurs after a change the reader made has been written to a task: the moment to save it.
TaskChangingOccurs before the reader changes a task – moves it, changes its length, records progress, or edits a cell – so that the application can refuse the change.
TaskToggledOccurs when a summary task is opened or closed, by the reader or by SetExpanded, ExpandAll, CollapseAll, or by selecting or scrolling to a task inside a closed summary.
ZoomChangedOccurs when Zoom changes, by the property, a zoom method, Ctrl and the wheel, or Ctrl and Plus or Minus.

Constructors

GanttChart

public GanttChart()

Creates a Gantt chart with an empty plan: empty, watched Tasks, Links and Holidays collections, a Monday-to-Friday week, and the timeline at GanttZoom.Week.

Remarks

Add tasks and links to the collections it starts with, or replace them with collections of your own.

Properties

BackColor

public override Color BackColor

Gets or sets the background of both panes, behind the rows and the timeline.

Value
The default is SystemColors.Window, as for a list or a grid, rather than the grey of a dialog that a control would otherwise take from its form.
Designer category
Appearance
Remarks

The grid lines, weekend shading, links and headers are worked out from this colour and Control.ForeColor unless set on their own, so these two are all a dark theme needs. Setting Color.Empty returns to the default. In Windows high-contrast mode the system colours are used instead.

Example
// A dark chart: everything structural follows these two colours.
gantt.BackColor = Color.FromArgb(0x1E, 0x1F, 0x22);
gantt.ForeColor = Color.FromArgb(0xE6, 0xE6, 0xE6);

BarColor

public Color BarColor

Gets or sets the colour of a task bar: its finished part and its outline are drawn in it, and the rest of the bar in a lighter tint of it.

Value
The default is a mid blue, #3B6EC4. Setting Color.Empty returns to the default.
Designer category
Appearance
Remarks

In Windows high-contrast mode the system colours are used instead.

BaselineColor

public Color BaselineColor

Gets or sets the colour of the thin baseline bar drawn under a task's bar.

Value
The default is a light grey, #A3ACB9. Setting Color.Empty returns to the default.
Designer category
Appearance
Remarks

Used only while ShowBaselines is on. In Windows high-contrast mode the system colours are used instead.

Columns

public GanttColumns Columns

Gets or sets which columns the task list shows beside the task's name.

Value
A combination of GanttColumns flags. The default is GanttColumns.Default: outline number, name, start, finish, duration and predecessors. The name is always shown, whether or not GanttColumns.Name is set.
Default
GanttColumns.Default
Designer category
Layout
Remarks

The columns appear in a fixed order whatever the combination: outline number (#), name (Task), Start, Finish, duration (Days), progress (% done), Assignee and Predecessors. Of these the reader can edit the name, the start, the duration, the progress and the predecessors, and only for a task that has that value of its own: a summary's dates, length and progress come from its subtasks, so only its name and predecessors can be typed.

Changing the columns closes a cell editor that is open, without applying it.

Example
gantt.Columns = GanttColumns.Default | GanttColumns.Assignee | GanttColumns.Progress;

CriticalBarColor

public Color CriticalBarColor

Gets or sets the colour of the tasks and links on the critical path – the ones that cannot slip without moving the finish.

Value
The default is an orange red, #E0592A. Setting Color.Empty returns to the default.
Designer category
Appearance
Remarks

Used only while ShowCriticalPath is on. In Windows high-contrast mode the system colours are used instead.

GridLineColor

public Color GridLineColor

Gets or sets the colour of the lines between rows and columns, in the task list and on the timeline.

Value
The default is Color.Empty, which mixes a little of Control.ForeColor into BackColor.
Designer category
Appearance
Remarks

In Windows high-contrast mode the system colours are used instead.

GridWidth

public int GridWidth

Gets or sets the width of the task list, the left-hand pane.

Value
In logical pixels (1/96 inch), scaled with the display. The default is 420.
Default
DefaultGridWidth
Designer category
Layout
Exceptions
ArgumentOutOfRangeException
The value is negative.
Remarks

The reader changes it by dragging the splitter between the panes. The task list is never drawn so wide that less than 48 logical pixels of timeline are left; the property keeps the value set. A task list wider than its columns widens the name column; a narrower one scrolls sideways under its own scroll bar.

Set it to 0 to show the timeline alone.

HeaderBackColor

public Color HeaderBackColor

Gets or sets the background of the column headings and the two rows of dates over the timeline.

Value
The default is Color.Empty, which is a faint tint of Control.ForeColor over BackColor.
Designer category
Appearance
Remarks

In Windows high-contrast mode the system colours are used instead.

Holidays

public IList<DateTime> Holidays

Gets or sets the dates that are not worked, such as public holidays and a Christmas shutdown.

Value
Dates; only their date part is read. Never null: the chart starts with an empty ObservableCollection, and setting null gives a new empty one.
Remarks

Durations and lags skip these dates, and the timeline shades them as it shades the days that WorkingWeek leaves out. An observable collection is watched; after changing a plain list, call Reschedule.

Example
foreach (DateTime holiday in new[] { new DateTime(2026, 12, 25), new DateTime(2026, 12, 28), new DateTime(2027, 1, 1) })
{
    gantt.Holidays.Add(holiday);
}

LinkColor

public Color LinkColor

Gets or sets the colour of the link arrows that are not on the critical path.

Value
The default is Color.Empty, which is a muted Control.ForeColor, part way to BackColor.
Designer category
Appearance
Remarks

In Windows high-contrast mode the system colours are used instead.

NonWorkingDayColor

public Color NonWorkingDayColor

Gets or sets the shading behind weekends, holidays and any other day the plan does not work.

Value
The default is Color.Empty, which is a faint tint of Control.ForeColor over BackColor.
Designer category
Appearance
Remarks

In Windows high-contrast mode the system colours are used instead.

ProjectStart

public DateTime? ProjectStart

Gets or sets the first day work can happen. No task is scheduled before it, except one that must start on an earlier date.

Value
A date; only its date part is kept, and a day that is not worked is moved to the next working day. The default is null, which takes the earliest planned ProjectTask.Start in the plan, then the earliest planned ProjectTask.Finish, and failing both, today's date.
Default
null
Designer category
Behavior
Remarks

Changing it schedules the plan again. Set it explicitly for a plan whose tasks have no planned dates, so that the chart does not start the plan on whatever day it is opened.

ReadOnly

public bool ReadOnly

Gets or sets whether the reader is stopped from changing the plan.

Value
true to stop editing. The default is false.
Default
false
Designer category
Behavior
Remarks

While it is on, bars cannot be dragged (pressing one pans the timeline instead), links cannot be drawn or deleted, cells cannot be edited and Shift with an arrow moves nothing. Selecting, scrolling, zooming, opening and closing summaries and TaskActivated still work, and the application can still change the tasks and links directly. Turning it on cancels a drag or cell edit in progress.

RowHeight

public int RowHeight

Gets or sets the height of a row, in the task list and on the timeline alike.

Value
In logical pixels (1/96 inch), from 12 to 400. The default is 28. A row is never drawn lower than the font needs, so a large font makes rows taller than this.
Default
DefaultRowHeight
Designer category
Layout
Exceptions
ArgumentOutOfRangeException
The value is below 12 or above 400.
Remarks

Changing it closes a cell editor that is open, without applying it.

SelectedTask

public ProjectTask SelectedTask

Gets or sets the task whose row is selected.

Value
A task in Tasks, or null (the default) when no row is selected.
Remarks

Setting a task opens the summaries it is in and scrolls its row into view; setting a task that is not in the plan clears the selection. SelectedTaskChanged follows either way.

When the selected task leaves the plan, the selection is cleared and SelectedTaskChanged is raised from the message loop. Closing a summary that holds the selected task moves the selection to the summary.

See also

ShowBaselines

public bool ShowBaselines

Gets or sets whether each task's baseline – the dates originally agreed for it – is drawn as a thin bar under its current bar, so slippage shows at a glance.

Value
true to draw baselines. The default is false.
Default
false
Designer category
Appearance
Remarks

A task has a baseline when its ProjectTask.BaselineStart is set; it runs to ProjectTask.BaselineFinish, or is one day long without it. It is drawn in BaselineColor.

ShowCriticalPath

public bool ShowCriticalPath

Gets or sets whether the tasks and links on the critical path – the ones that cannot slip without moving the finish – are drawn in CriticalBarColor.

Value
true (the default) to pick out the critical path; false to draw every task in BarColor.
Default
true
Designer category
Appearance

ShowToday

public bool ShowToday

Gets or sets whether a line is drawn down the timeline at today's date, in TodayColor.

Value
true (the default) to draw it. The date is Today, or the computer's date.
Default
true
Designer category
Appearance

SummaryBarColor

public Color SummaryBarColor

Gets or sets the colour of a summary task's bracket and of a milestone's diamond.

Value
The default is a slate grey, #5A6472. Setting Color.Empty returns to the default.
Designer category
Appearance
Remarks

In Windows high-contrast mode the system colours are used instead.

Tasks

public IList<ProjectTask> Tasks

Gets or sets the tasks of the plan, in outline order within each parent.

Value
The tasks. Never null: the chart starts with an empty ObservableCollection, and setting null gives a new empty one.
Remarks

An ObservableCollection or a BindingList is watched, and so is every task in it, so adding, removing and changing tasks reschedules and redraws the chart. A plain list such as a List is read when it is assigned; call Reschedule after changing one.

The order of the list is the order of the rows within each summary. Setting a new list cancels any drag or cell edit in progress. The reader's choice of open and closed summaries is kept by task id, so it survives a fresh copy of the same plan.

See also

Today

public DateTime? Today

Gets or sets the date the today line is drawn at.

Value
A date; only its date part is kept. The default is null, which uses the computer's date each time the chart is painted.
Default
null
Designer category
Appearance
Remarks

It moves the line and nothing else: the plan is scheduled from ProjectStart, not from today. Set it to review a plan as it stood on another day, or to keep screenshots reproducible. The line is drawn only while ShowToday is on.

TodayColor

public Color TodayColor

Gets or sets the colour of the line drawn down the timeline at today's date.

Value
The default is a violet, #7B4FD6. Setting Color.Empty returns to the default.
Designer category
Appearance
Remarks

Used only while ShowToday is on. In Windows high-contrast mode the system colours are used instead.

WeekStart

public DayOfWeek WeekStart

Gets or sets the day each week starts on in the timeline's headings.

Value
The default is Monday.
Default
DayOfWeek.Monday
Designer category
Appearance
Exceptions
System.ComponentModel.InvalidEnumArgumentException
The value is not a DayOfWeek.
Remarks

At GanttZoom.Week zoom each week's column is labelled with the date of this day, and at GanttZoom.Day and GanttZoom.Week zoom the timeline begins and ends on it. It changes only the timeline, never the working week or the schedule.

WorkingWeek

public WorkingWeek WorkingWeek

Gets or sets the days of the week that are worked. Durations and lags count only these days, and the timeline shades the others.

Value
A combination of WorkingWeek flags. The default is WorkingWeek.Weekdays, Monday to Friday; WorkingWeek.None is read as every day being worked.
Default
WorkingWeek.Weekdays
Designer category
Behavior

Zoom

public GanttZoom Zoom

Gets or sets how much time the timeline shows, from a column per day to a column per half-year.

Value
The default is GanttZoom.Week.
Default
GanttZoom.Week
Designer category
Appearance
Exceptions
System.ComponentModel.InvalidEnumArgumentException
The value is not a GanttZoom.
Remarks

When the zoom changes, the date in the middle of the timeline stays in the middle, and ZoomChanged is raised. The reader changes it with Ctrl and the wheel (holding the date under the pointer still) or Ctrl and Plus or Minus. ZoomToFit picks the zoom that shows the whole plan.

See also

Methods

CollapseAll

public void CollapseAll()

Closes every summary task, leaving only the top-level rows. TaskToggled is raised for each summary that was open.

Remarks

A selected task inside a summary passes the selection up to its top-level summary.

CreateAccessibilityInstance

protected override AccessibleObject CreateAccessibilityInstance()

Creates the accessible object that presents the chart to screen readers and other assistive technology as an outline: one item per visible row, each saying the task's name, dates, length, progress and whether it is critical.

Returns

The chart's accessible object.

CreatePrintDocument

public PrintDocument CreatePrintDocument()

Creates a document that prints the whole chart, with every task shown and every summary open.

Returns

A PrintDocument named "Project plan". The caller owns it and must dispose it.

Remarks

A chart a little wider than the page's margins is shrunk to fit, down to half its size; a wider one continues on further pages. Pages run down the plan first and then across it, every page ends on a whole row, and the column and date headings are repeated at the top of each page. The current Zoom, Columns and colours are used.

The plan is read when each page is printed, not when the document is created, so a document kept for a print preview prints the plan as it is at that time. Set the document's printer and page settings before printing, as for any PrintDocument.

Example
using (PrintDocument document = gantt.CreatePrintDocument())
using (PrintPreviewDialog preview = new PrintPreviewDialog { Document = document })
{
    document.DefaultPageSettings.Landscape = true;
    preview.ShowDialog(this);
}

Dispose

protected override void Dispose(bool disposing)

Stops watching the plan and releases the fonts, the tooltip and the timer the chart created. The scroll bars and the cell editor are child controls and are released with the chart.

Parameters
disposing
true when called from Dispose(); false from the finaliser.
Remarks

The application's tasks, links and holidays are not touched: they can be given to another chart.

EnsureSchedule

public ProjectSchedule Schedule

Gets the plan as the chart has scheduled it: every task's dates and float, the links that were honoured, the critical path, the project's start and finish, and anything in the plan that could not be used.

Value
Never null.
Remarks

Worked out again first whenever anything in the plan has changed, so reading it straight after changing a task gives the new dates. The schedule returned is a snapshot; read the property again after a change rather than keeping it.

Example
ProjectSchedule schedule = gantt.Schedule;
if (schedule.Problems.Count > 0)
{
    MessageBox.Show(this, string.Join(Environment.NewLine, schedule.Problems), "Problems in the plan");
}

ExpandAll

public void ExpandAll()

Opens every summary task, so every task has a row. TaskToggled is raised for each summary that was closed.

ExportImage

public Bitmap ExportImage()

Draws the whole chart into a new image: the task list and the timeline side by side, with every task shown and every summary open, across the plan's whole span.

Returns

A 24-bit image at 96 DPI. The caller owns it and must dispose it.

Exceptions
InvalidOperationException
The plan is too large for one image at this zoom.
Remarks

The image is drawn at the current Zoom, Columns and colours, and is the same on every monitor: it is drawn at 96 DPI in the chart's font at its 96 DPI size, whatever the display's scale. Selection, focus and hover are not drawn, so the image is a record of the plan rather than of the screen. An empty plan gives a small image holding the chart's empty-plan message.

A long plan at a fine zoom makes a very large image; zoom out first, or print it with CreatePrintDocument, which spreads it across pages.

Example
using (Bitmap image = gantt.ExportImage())
{
    image.Save(Path.Combine(reportFolder, "plan.png"), ImageFormat.Png);
}

IsExpanded

public bool IsExpanded(ProjectTask task)

Tells whether a summary task's subtasks are shown.

Parameters
task
The task.
Returns

true for an open summary; false for a closed one, for a task that is not a summary, and for one not in the plan.

IsInputKey

protected override bool IsInputKey(Keys keyData)

Claims the keys the chart uses for itself, so that the form does not take them for moving the focus or pressing a button.

Parameters
keyData
The key, with its modifiers.
Returns

true for the arrows, Home, End, Page Up and Page Down; for Enter without Alt, which activates the selected task instead of pressing the form's default button; and for Esc while a drag is in progress. Otherwise what the base class answers.

OnBackColorChanged

protected override void OnBackColorChanged(EventArgs e)

Raises Control.BackColorChanged and redraws with the new background, and the colours worked out from it.

Parameters
e
Empty event data.

OnDpiChangedAfterParent

protected override void OnDpiChangedAfterParent(EventArgs e)

Lays the chart out again when it moves to a display with a different scale, so that every logical size is converted at the new DPI and the fonts are rebuilt.

Parameters
e
Empty event data.

OnFontChanged

protected override void OnFontChanged(EventArgs e)

Rebuilds the bold font summaries are written in and lays the chart out again for the new font, then raises Control.FontChanged.

Parameters
e
Empty event data.

OnForeColorChanged

protected override void OnForeColorChanged(EventArgs e)

Raises Control.ForeColorChanged and redraws with the new text colour, and the colours worked out from it.

Parameters
e
Empty event data.

OnGotFocus

protected override void OnGotFocus(EventArgs e)

Redraws the selection in its focused colour and announces it to screen readers. Tabbing into a chart with nothing selected selects the first row, so the keyboard has somewhere to start.

Parameters
e
Empty event data.

OnHandleCreated

protected override void OnHandleCreated(EventArgs e)

Raises any schedule and selection events that were held back until the chart had a window.

Parameters
e
Empty event data.

OnHandleDestroyed

protected override void OnHandleDestroyed(EventArgs e)

Forgets notifications posted to a window that is going away; the next window posts them again.

Parameters
e
Empty event data.

OnKeyDown

protected override void OnKeyDown(KeyEventArgs e)

Raises Control.KeyDown, then carries out the chart's keyboard commands – moving between rows and cells, moving and stretching tasks, zooming, editing – unless a handler has already handled the key. The keys are listed in the remarks on GanttChart.

Parameters
e
The key and its modifiers. Set as handled when the chart acts on it.

OnLinksChanged

protected virtual void OnLinksChanged(EventArgs e)

Raises the LinksChanged event.

Parameters
e
Empty event data.
Remarks

A derived chart that overrides this should call the base method, or the event is not raised.

OnLinksChanging

protected virtual void OnLinksChanging(LinksChangingEventArgs e)

Raises the LinksChanging event.

Parameters
e
The proposed change. Set its CancelEventArgs.Cancel to refuse it.
Remarks

The chart reads CancelEventArgs.Cancel after this returns. A derived chart can refuse a change here, before or instead of calling the base method.

OnLostFocus

protected override void OnLostFocus(EventArgs e)

Redraws the selection in its unfocused colour.

Parameters
e
Empty event data.

OnMouseCaptureChanged

protected override void OnMouseCaptureChanged(EventArgs e)

Abandons a drag without applying it when the mouse is taken away part way through – by a dialog opening or the window losing activation – as Esc does.

Parameters
e
Empty event data.

OnMouseDoubleClick

protected override void OnMouseDoubleClick(MouseEventArgs e)

Raises Control.MouseDoubleClick, then raises TaskActivated when the double-click was on a task's row in the task list or on its bar.

Parameters
e
The button, position and click count.

OnMouseDown

protected override void OnMouseDown(MouseEventArgs e)

Raises Control.MouseDown, then acts on the press: selects the row under it, opens or closes a summary at its expander, or begins dragging the splitter, a bar, a bar's end, its progress, a new link, or the timeline itself. A right-click selects the row, so a context menu acts on what was clicked.

Parameters
e
The button, position and click count.

OnMouseLeave

protected override void OnMouseLeave(EventArgs e)

Raises Control.MouseLeave and clears the hover highlight, unless a drag is in progress.

Parameters
e
Empty event data.

OnMouseMove

protected override void OnMouseMove(MouseEventArgs e)

Raises Control.MouseMove, then moves a drag in progress, or updates the hover highlight, the pointer shape and the tooltip for what is under the pointer.

Parameters
e
The button, position and click count.

OnMouseUp

protected override void OnMouseUp(MouseEventArgs e)

Raises Control.MouseUp, then finishes a drag: a bar moved or stretched, progress or a link is offered through TaskChanging or LinksChanging.

Parameters
e
The button, position and click count.

OnMouseWheel

protected override void OnMouseWheel(MouseEventArgs e)

Raises Control.MouseWheel, then scrolls the rows by the system's lines per notch; with Shift, scrolls sideways the pane under the pointer; with Ctrl, zooms one step per notch about the date under the pointer.

Parameters
e
The wheel's movement and the pointer's position.

OnPaint

protected override void OnPaint(PaintEventArgs e)

Draws the task list, the splitter, the timeline and the headers, then raises Control.Paint. A fault while drawing is absorbed rather than leaving the control crossed out, and the next paint tries again.

Parameters
e
The graphics to draw with and the area to draw.

OnResize

protected override void OnResize(EventArgs e)

Raises Control.Resize and lays the panes and scroll bars out for the new size.

Parameters
e
Empty event data.

OnScheduleChanged

protected virtual void OnScheduleChanged(EventArgs e)

Raises the ScheduleChanged event.

Parameters
e
Empty event data.
Remarks

A derived chart that overrides this should call the base method, or the event is not raised.

OnSelectedTaskChanged

protected virtual void OnSelectedTaskChanged(EventArgs e)

Raises the SelectedTaskChanged event.

Parameters
e
Empty event data.
Remarks

A derived chart that overrides this should call the base method, or the event is not raised.

OnTaskActivated

protected virtual void OnTaskActivated(TaskEventArgs e)

Raises the TaskActivated event.

Parameters
e
The task that was activated.
Remarks

A derived chart that overrides this should call the base method, or the event is not raised.

OnTaskChanged

protected virtual void OnTaskChanged(TaskEventArgs e)

Raises the TaskChanged event.

Parameters
e
The task that changed.
Remarks

A derived chart that overrides this should call the base method, or the event is not raised.

OnTaskChanging

protected virtual void OnTaskChanging(TaskChangingEventArgs e)

Raises the TaskChanging event.

Parameters
e
The proposed change. Set its CancelEventArgs.Cancel to refuse it.
Remarks

The chart reads CancelEventArgs.Cancel after this returns. A derived chart can refuse a change here, before or instead of calling the base method.

OnTaskToggled

protected virtual void OnTaskToggled(TaskEventArgs e)

Raises the TaskToggled event.

Parameters
e
The summary that was opened or closed.
Remarks

A derived chart that overrides this should call the base method, or the event is not raised.

OnZoomChanged

protected virtual void OnZoomChanged(EventArgs e)

Raises the ZoomChanged event.

Parameters
e
Empty event data.
Remarks

A derived chart that overrides this should call the base method, or the event is not raised.

Reschedule

public void Reschedule()

Schedules the plan again now, redraws, and raises ScheduleChanged.

Remarks

Needed only after changing a plain list – adding to a List given to Tasks, Links or Holidays – which the chart cannot watch. Observable collections and the task and link objects themselves are watched. Any drag of a bar in progress is cancelled.

Example
List<ProjectTask> tasks = LoadTasksFromDatabase();
gantt.Tasks = tasks;

tasks.Add(new ProjectTask("training", "Train the support desk", 2));
gantt.Reschedule();   // a List<T> says nothing when it changes

ResetBackColor

public override void ResetBackColor()

Returns BackColor to its default, SystemColors.Window. The Properties window's Reset command calls this.

ScrollToTask

public void ScrollToTask(ProjectTask task)

Scrolls a task's row and bar into view, opening the summaries it is in.

Parameters
task
The task. Nothing happens for null or a task that is not in the plan.
Remarks

The selection is left as it is; set SelectedTask to select the task as well, which scrolls to it too. Opening a closed summary on the way raises TaskToggled.

ScrollToToday

public void ScrollToToday()

Scrolls the timeline so that today's date – Today, or the computer's date – is a third of the way across it.

SetExpanded

public void SetExpanded(ProjectTask task, bool expanded)

Opens or closes a summary task.

Parameters
task
The summary. Nothing happens for a task that is not a summary, or not in the plan.
expanded
true to show its subtasks, false to hide them.
Remarks

Raises TaskToggled when the summary changes state. Closing a summary that holds the selected task moves the selection to the summary. The choice is remembered by task id for as long as the chart lives, and outranks the task's own ProjectTask.IsCollapsed.

Size

protected override Size DefaultSize

Gets the size the chart is given when it is first placed on a form: room for the task list and a few weeks of timeline.

Value
720 by 360 logical pixels.

ZoomIn

public void ZoomIn()

Shows less time in more detail: one GanttZoom step finer, keeping the date in the middle of the timeline where it is. Does nothing at GanttZoom.Day.

ZoomOut

public void ZoomOut()

Shows more time in less detail: one GanttZoom step coarser, keeping the date in the middle of the timeline where it is. Does nothing at GanttZoom.Year.

ZoomToFit

public void ZoomToFit()

Picks the finest zoom at which the whole plan fits across the timeline without scrolling sideways, and scrolls to the plan's start.

Remarks

A fortnight is allowed beyond the plan's last day, so the labels and links of the last bars still fit. Call it once the chart has its final size – from the form's Load or Shown event, say – since the fit depends on the width of the timeline. Does nothing for an empty plan.

Example
Shown += (sender, e) => gantt.ZoomToFit();

Events

LinksChanged

public event EventHandler LinksChanged

Occurs after links the reader added or removed have been written to Links.

Designer category
Action

LinksChanging

public event EventHandler<LinksChangingEventArgs> LinksChanging

Occurs before the reader adds or removes links – a link drawn between two bars, a predecessor list typed into a cell, or a selected link deleted – so that the application can refuse the change.

Designer category
Action
Remarks

Set CancelEventArgs.Cancel to true to refuse it. Otherwise the links are removed from and added to Links, and LinksChanged follows. Not raised when Links is read-only, since nothing could be changed.

See also

ScheduleChanged

public event EventHandler ScheduleChanged

Occurs after the plan has been scheduled again because something in it changed: a task, a link, a collection, a holiday, ProjectStart or WorkingWeek.

Designer category
Action
Remarks

Raised from the message loop, once for any number of changes made together – an import of three hundred tasks raises it once, not three hundred times – and immediately by Reschedule. Read Schedule in the handler for the new dates; the handler may change the plan again.

SelectedTaskChanged

public event EventHandler SelectedTaskChanged

Occurs when SelectedTask changes, by the reader, by the application, or because the selected task left the plan.

Designer category
Behavior

TaskActivated

public event EventHandler<TaskEventArgs> TaskActivated

Occurs when the reader double-clicks a task's row or bar, or presses Enter or Space with its row selected: the moment to open the application's own view of the task.

Designer category
Action

TaskChanged

public event EventHandler<TaskEventArgs> TaskChanged

Occurs after a change the reader made has been written to a task: the moment to save it.

Designer category
Action
Remarks

Raised after TaskChanging was not cancelled. The plan has been marked for scheduling again; ScheduleChanged follows from the message loop.

TaskChanging

public event EventHandler<TaskChangingEventArgs> TaskChanging

Occurs before the reader changes a task – moves it, changes its length, records progress, or edits a cell – so that the application can refuse the change.

Designer category
Action
Remarks

Set CancelEventArgs.Cancel to true to refuse it: nothing is written and the bar or cell goes back to how it was. Otherwise the new values are written to the task and TaskChanged follows. The event is raised for the reader's edits only; a change the application makes to a task directly is not offered here.

See also

TaskToggled

public event EventHandler<TaskEventArgs> TaskToggled

Occurs when a summary task is opened or closed, by the reader or by SetExpanded, ExpandAll, CollapseAll, or by selecting or scrolling to a task inside a closed summary.

Designer category
Action
Remarks

The event data's task is the summary. Use IsExpanded to tell which way it went.

ZoomChanged

public event EventHandler ZoomChanged

Occurs when Zoom changes, by the property, a zoom method, Ctrl and the wheel, or Ctrl and Plus or Minus.

Designer category
Property Changed