Reputation: 2523
I have a little loop function that resizes the columns based on the width of the text of the Column Header:
var columns = VView.gridViewCblID.Columns;
foreach (DataGridViewColumn clm in columns)
{
VView.lblDummy.Text = clm.HeaderText;
if (clm.Width > VView.lblDummy.Width && clm.Width <= 100)
{
clm.Width = VView.lblDummy.Width;
}
}
However, due to a "cushion" that is automatically applied to the left of the Column HeaderText, the columns get a "bunched" appearance:
What is the actual width of that cushion, so I can apply it to the method? I.e.
clm.Width = VView.lblDummy.Width + (cushion *2);
Upvotes: 0
Views: 84
Reputation: 5266
It's possible to use AutoSizeColumnsMode
to do the work for you, and then set the resize mode back to manual. E.g.
DataGridView dgv = new DataGridView() { Dock = DockStyle.Fill };
dgv.Columns.Add("Cable Number", "Cable Number");
dgv.Columns.Add("Type", "Type");
dgv.Columns.Add("Length", "Length");
dgv.Columns["Type"].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
Form f = new Form();
f.Controls.Add(dgv);
dgv.HandleCreated += delegate {
dgv.BeginInvoke((Action) delegate {
var c = dgv.Columns["Type"];
int w = c.Width;
c.Width = w; // set current width, otherwise DGV reverts to previous 100 width
c.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
});
};
Upvotes: 3