Adding new columns to a Winforms DataGridView via code

前端 未结 4 2368
情歌与酒
情歌与酒 2021-02-19 05:43

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 <= d         


        
相关标签:
4条回答
  • 2021-02-19 06:12

    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() });
            }
    
    0 讨论(0)
  • 2021-02-19 06: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() });
    }
    
    0 讨论(0)
  • 2021-02-19 06:28

    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.

    0 讨论(0)
  • 2021-02-19 06:35

    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.

    0 讨论(0)
提交回复
热议问题