Skip to content

Commit

Permalink
Merge pull request #54 from solarwinds/td/AutoSizeColumns
Browse files Browse the repository at this point in the history
Implement hacky 'smart' auto column sizing
  • Loading branch information
derhally authored Feb 2, 2017
2 parents e545cdf + 7dfe38e commit 8c796f3
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions Src/SwqlStudio/QueryTab.cs
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,7 @@ private void queryWorker_RunWorkerCompleted(object sender, System.ComponentModel
}

grid.DataSource = arg.Results;
AutoResizeColumns(grid);
}

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

private static void AutoResizeColumns(DataGridView grid)
{
const int maxSize = 200;
const int widthFudgeFactor = 25;

int[] preferredSizes = new int[grid.ColumnCount];
int excessPreferredSize = 0;
int totalCurrentColumnSize = 0;
grid.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
for (int i = 0; i < grid.ColumnCount; i++)
{
DataGridViewColumn column = grid.Columns[i];
preferredSizes[i] = column.Width;
if (column.Width > maxSize)
{
excessPreferredSize += column.Width - maxSize;
column.Width = maxSize;
}
totalCurrentColumnSize += column.Width;
}

if (excessPreferredSize > 0)
{
// Some columns would like to be larger. Can we do this without incurring horizontal scroll?
// Easiest to just always leave room for a vertical scroll bar
int availableWidth = grid.DisplayRectangle.Width - totalCurrentColumnSize
- SystemInformation.VerticalScrollBarWidth - widthFudgeFactor;
if (availableWidth > 0)
{
double grantRatio = Math.Min(1.0, (double)availableWidth / excessPreferredSize);
for (int i = 0; i < grid.ColumnCount; i++)
{
DataGridViewColumn column = grid.Columns[i];
if (column.Width != preferredSizes[i])
{
column.Width += (int)((preferredSizes[i] - column.Width) * grantRatio);
}
}
}
}
}

private void ShowLog(string lastReplyLog)
{
logTextbox.Text = lastReplyLog ?? string.Empty;
Expand Down

0 comments on commit 8c796f3

Please sign in to comment.