I try to control columns in Designer and to change the height of all rows in either Designer or Code. The following code and settings change the height of all rows but the first one like the image.
private void Form1_Load(object sender, EventArgs e)
{
Text = dataGridView1.Rows[0].Height.ToString(); // always 33
// in Designer
// RowTemplate.Height = 50
// AutoSizeRowsMode = none
}
After I fill the first row cell 50-height rows are created. Runtime code doesn't make any difference. To fix it I have to code dataGridView1.Rows[0].Height = 50
after the grid has been painted. Why this and how to implement that in Designer level?
CodePudding user response:
If you don't set a DataSource to your DataGridView, the Constructor of the Control caches default values of multiple properties (sets default states), then calls PerformLayout(); but, as you can see in the source code, the layout is set to:
SetState(States.LayoutDeferred, true);
//[...]
LayoutEngine.ProcessSuspendedLayoutEventArgs(this, args);.
The default layout doesn't consider the RowTemplate's Height
, since a default layout is applied.
When you set the DataSource, on the other hand, the OnDataSourceChanged() method is called and in turn InvalidateRowHeights() and RefreshColumnsAndRows(), so the layout is fully performed, including the RowTemplate's pre-set.
You have different ways to solve the current issue:
- Force the value to the first Row of the DataGridView, which, in this case, is the simply the New Row object, with, e.g,
dataGridView1.Rows[0].Height = dataGridView1.RowTemplate.Height;
, if you have predefined values that are applied to all Rows after (*) - Add a new empty Data Row, i.e.,
dataGridView1.Rows.Add();
- Set an empty DataSource then remove it, e.g.,
DataGridView1.DataSource = new BindingSource(); dataGridView1.DataSource = null;
- Set an actual DataSource
* Might have some issues when custom painting is in place, the related code should be designed to handle this