15

I'm trying to add N number of columns for each days of a given month:

var daysCount = DateTime.DaysInMonth(DateTime.Now.Year, month);

for (int i = 1; i <= daysCount; i++)
{
    dataGridView1.Columns.Add(new DataGridViewColumn() { HeaderText = i.ToString() });
}

I'm getting this error:

At least one of the DataGridView control's columns has no cell template.

4 Answers 4

15

When you create a new datagridview column it's pretty blank. You will need to set the celltemplate of the column so that it knows what controls to show for the cells in the grid. Alternatively I think if you use some of the stronger typed columns (DataGridViewTextBoxColumn) then you might be ok.

Sign up to request clarification or add additional context in comments.

Comments

10

The problem stems from your DataGridViewColumn.CellTemplate not being set.

For this scenario a DataGridViewTextBoxCell as the CellTemplate should suffice.

       var daysCount = DateTime.DaysInMonth(DateTime.Now.Year, 1);

        for (int i = 1; i <= daysCount; i++)
        {
            dataGridView1.Columns.Add(new DataGridViewColumn() { HeaderText = i.ToString(), CellTemplate = new DataGridViewTextBoxCell() });
        }

Comments

2

You need to specify first whether it's a textbox column or combobox column Try this it will work

var daysCount = DateTime.DaysInMonth(DateTime.Now.Year, month);

for (int i = 1; i <= daysCount; i++)
{
    dataGridView1.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = i.ToString() });
}

Comments

1

set your table and add needed columns. then use:

var daysCount = DateTime.DaysInMonth(DateTime.Now.Year, 1);

for (int i = 0; i <= daysCount; i++)
        {
          i = dataGridView1.Rows.Add(new DataGridViewRow());


                        dataGridView1.Rows[i].Cells["YourNameCell"].Value = i.ToString();

       }

Frist row is 0, not 1. probabily your error are these.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.