C# – DataGridView display row header cell

cdatagridviewnet

I'm trying to display a simple DataGridView linked to a DataTable and I want, ultimately, my first column in the DataTable to be the row header cell for the DataGridView. At this point I will settle for having any value in the row header cell. I can display the DataGridView with all my rows and columns, and with column header cells, but no row header cell. I check the value in the row.HeaderCell.Value, and the data I put there is there. I check row.HeaderCell.Displayed and it is false, but this is read only, so I can't make it true. How do I make the row header cell display?

Here's a simple sample of what I've tried to get this to work:

        DataTable table = new DataTable();
        for (int i = 0; i<10; i++)
        {
            table.Columns.Add(new DataColumn("column-" + i));
        }

        for (int i = 0; i < 10; i++)
        {
            DataRow theRow = table.NewRow();

            for (int j = 0; j < 10; j++)
                theRow[j] = i + "-" + j;
            table.Rows.Add(theRow);

        }

        dataGridView1.DataSource = table;
        dataGridView1.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders;
        int rowNumber = 1;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.IsNewRow) continue;
            row.HeaderCell.Value = "Row " + rowNumber;
            rowNumber = rowNumber + 1;
        }
        dataGridView1.AutoResizeRowHeadersWidth(
            DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);

Best Answer

If you place this code in the constructor, it will not work. Move the code into the form's Load event and it should work fine. A common problem with Windows.Forms and C# is the use of improper initialization in the constructor. Many controls are not fully created until after the constructor finishes. (I forget why, but I believe it is because the handle is not created yet.) Many "work arounds" can be avoided, if you initialize in the Load event as recommended by Microsoft.

Related Topic