Search code examples
c#winformsdatagridviewdatagridviewcellstyle

How to programmatically change empty DataGridView Cell back color?


I am making a gantt chart programatically. What I do is get the project's tasks bind it to the gridview, and then get the project duration in days, loop over it to add 1 additional column per day on the grid view. What I need to do is get the duration of each task, and then fill the corresponding cells in the grid.

i.e.
Project duration - 5 days.
task 1 duration - 2 days > needed: fiil 2/5 of dgv cells.

Is this possible?

EDIT

//GET PROJECT TASK
string GetTasks = "SELECT TaskName FROM CreateTask WHERE ProjectID='" + ProjectID_Txt.Text + "'";
DataTable ProjTasks_DT = new DataTable();
SqlDataAdapter ProjTasks_Adapter;

ProjTasks_Adapter = new SqlDataAdapter(GetTasks, connString);
ProjTasks_DT.Clear();
ProjTasks_Adapter.Fill(ProjTasks_DT);
connString.Close();

TaskTrackingGrd.DataSource = ProjTasks_DT;

//PROJECT DURATION IN HOURS
int DayDuration = ((Project_EndDate.Value - Project_StartDate.Value).Days) + 1;

//ADDS THE COLUMNS
for (int i = 0; i < DayDuration; i++) 
{
    var col3 = new DataGridViewTextBoxColumn();
    col3.HeaderText = "Day " + (i+1);
    TaskTrackingGrd.Columns.AddRange(new DataGridViewColumn[] { col3 });
}

Solution

  • Yes:

    int col, row;
    Color color;
    ...
    dgv[col, row].Style.BackColor = color;
    

    Suppose the task is row 1 and the project begins on day 2 and runs for 3 days:

    {    
        ShowTask(1, 2, 3, Color.Red);
    }
    
    void ShowTask(int taskRow, int startDay, int duration, Color color)
    {
        for (int day = startDay - 1; day < startDay + duration - 1; day++)
            dgv[day, taskRow].Style.BackColor = color;
    }