Skip to content

Commit 8c796f3

Browse files
authored
Merge pull request #54 from solarwinds/td/AutoSizeColumns
Implement hacky 'smart' auto column sizing
2 parents e545cdf + 7dfe38e commit 8c796f3

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Src/SwqlStudio/QueryTab.cs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,7 @@ private void queryWorker_RunWorkerCompleted(object sender, System.ComponentModel
356356
}
357357

358358
grid.DataSource = arg.Results;
359+
AutoResizeColumns(grid);
359360
}
360361

361362
queryStatusBar1.UpdateValues(arg.Results.Rows.Count, arg.QueryTime, (long?)arg.Results.ExtendedProperties["TotalRows"]);
@@ -416,6 +417,48 @@ from error in arg.Errors
416417
}
417418
}
418419

420+
private static void AutoResizeColumns(DataGridView grid)
421+
{
422+
const int maxSize = 200;
423+
const int widthFudgeFactor = 25;
424+
425+
int[] preferredSizes = new int[grid.ColumnCount];
426+
int excessPreferredSize = 0;
427+
int totalCurrentColumnSize = 0;
428+
grid.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
429+
for (int i = 0; i < grid.ColumnCount; i++)
430+
{
431+
DataGridViewColumn column = grid.Columns[i];
432+
preferredSizes[i] = column.Width;
433+
if (column.Width > maxSize)
434+
{
435+
excessPreferredSize += column.Width - maxSize;
436+
column.Width = maxSize;
437+
}
438+
totalCurrentColumnSize += column.Width;
439+
}
440+
441+
if (excessPreferredSize > 0)
442+
{
443+
// Some columns would like to be larger. Can we do this without incurring horizontal scroll?
444+
// Easiest to just always leave room for a vertical scroll bar
445+
int availableWidth = grid.DisplayRectangle.Width - totalCurrentColumnSize
446+
- SystemInformation.VerticalScrollBarWidth - widthFudgeFactor;
447+
if (availableWidth > 0)
448+
{
449+
double grantRatio = Math.Min(1.0, (double)availableWidth / excessPreferredSize);
450+
for (int i = 0; i < grid.ColumnCount; i++)
451+
{
452+
DataGridViewColumn column = grid.Columns[i];
453+
if (column.Width != preferredSizes[i])
454+
{
455+
column.Width += (int)((preferredSizes[i] - column.Width) * grantRatio);
456+
}
457+
}
458+
}
459+
}
460+
}
461+
419462
private void ShowLog(string lastReplyLog)
420463
{
421464
logTextbox.Text = lastReplyLog ?? string.Empty;

0 commit comments

Comments
 (0)