delete
delete

Reputation:

Adding new columns to a Winforms DataGridView via code

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.

Upvotes: 15

Views: 29860

Answers (4)

user1969179
user1969179

Reputation: 21

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() });
}

Upvotes: 2

devilkkw
devilkkw

Reputation: 438

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.

Upvotes: 1

Aaron McIver
Aaron McIver

Reputation: 24723

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() });
        }

Upvotes: 10

Tony Abrams
Tony Abrams

Reputation: 4673

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.

Upvotes: 15

Related Questions