フォームに合わせて DataGridView を自動的にサイズ変更するはじめに この記事では、フォームのサイズを変更した後に、常にそのサイズに合わせて 注 DataGridViewクラスは、Windows Form 2.0に含まれる新しいコントロールです。.NET Framework 1.1では利用できません。解説このコードで最も重要なのは、すべての列の幅を再計算する処理です(可視列がある場合)。しかし、最後の部分で丸め誤差が生じると、最終列の幅が1ピクセルから数ピクセル広くなってしまい、スクロールバーが表示されることがあります。それを避けるため、最後に、最終列に必要な幅を正確に計算します。 これについて、重要なコード部分を示しながら説明していきます。 int fixedWidth = SystemInformation.VerticalScrollBarWidth + dataGrid.RowHeadersWidth + 2; int mul = 100 * (dataGrid.Width - fixedWidth) / (prevWidth - fixedWidth); まず、データグリッドの固定幅( 次に、データグリッドのすべての可視列を反復処理して、新しい幅を計算します。もちろん、 columnWidth = (dataGrid.Columns[i].Width * mul + 50) / 100; dataGrid.Columns[i].Width = Math.Max(columnWidth, dataGrid.Columns[i].MinimumWidth); ここで 最後にすべきことは、最終列の正確な幅を調べることです。これが必要なのは、丸め誤差が生じたり、一部の列の 完全なコード
public void ResizeGrid(DataGridView dataGrid, ref int prevWidth) { if (prevWidth == 0) prevWidth = dataGrid.Width; if (prevWidth == dataGrid.Width) return; int fixedWidth = SystemInformation.VerticalScrollBarWidth + dataGrid.RowHeadersWidth + 2; int mul = 100 * (dataGrid.Width - fixedWidth) / (prevWidth - fixedWidth); int columnWidth; int total = 0; DataGridViewColumn lastVisibleCol = null; for (int i = 0; i < dataGrid.ColumnCount; i++) if (dataGrid.Columns[i].Visible) { columnWidth = (dataGrid.Columns[i].Width * mul + 50) / 100; dataGrid.Columns[i].Width = Math.Max(columnWidth, dataGrid.Columns[i].MinimumWidth); total += dataGrid.Columns[i].Width; lastVisibleCol = dataGrid.Columns[i]; } if (lastVisibleCol == null) return; columnWidth = dataGrid.Width - total + lastVisibleCo .Width - fixedWidth; lastVisibleCol.Width = Math.Max(columnWidth, lastVisibleCol.MinimumWidth); prevWidth = dataGrid.Width; } テストアプリケーション これは、 テストアプリケーションの完全なコードは次のとおりです。 namespace ResizeGridDemo { public partial class main: Form { int prevWidth; FormWindowState prevWindowState; public main() { InitializeComponent(); prevWidth = Width; prevWindowState = WindowState; } private void main_ResizeEnd(object sender, EventArgs e) { ResizeGrid(dataGrid, ref prevWidth); } private void main_Resize(object sender, EventArgs e) { if (WindowState != prevWindowState && WindowState != FormWindowState.Minimized) { prevWindowState = WindowState; ResizeGrid(dataGrid, ref prevWidth); } } } } まとめ これらすべてのコードをフォームに記述することもできますが、 注意
動作確認はVS 2005 Beta 2で行いました。
このコードをプロジェクト内で使用する場合は、1回だけ記述すれば済みます(たとえば 著者紹介Wilfriend Mestdagh(Wilfriend Mestdagh)
|