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 Answers4

14

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.

Tony Abrams
  • 4,505
  • 3
  • 25
  • 32
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() });
        }
Aaron McIver
  • 24,527
  • 5
  • 59
  • 88
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() });
}
Matt
  • 74,352
  • 26
  • 153
  • 180
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.

devilkkw
  • 418
  • 2
  • 6
  • 17