如果网格较小,则调整DataGridView的列以填充可用空间,并在网格大于可用空间的情况下使用滚动

joa*_*spf 9 .net c# datagridview

我想根据所需的空间调整DataGridView的所有列,以完全显示其所有数据.如果所需空间小于可用空间我希望网格填充这个超出空间,但如果可用空间不足以正确显示我想要DataGridView的所有列自动创建滚动.是否有捷径可寻?

小智 9

单击DataGridView并选择"Edit Columns ...",然后转到"Layout"并将"AutoSizeMode"设置为"Fill".

希望这是你正在寻找的.

干杯


the*_*bit 5

如果您希望保持表 (DataGridView) 的格式,以便自动调整所有列的大小,但特别是一列填充剩余空间,您可以执行以下操作:

//Store the number of columns in a variable
int columnCount = dataGridView.Columns.Count;

//If we want the last column to fill the remaining space
int lastColumnIndex = columnCount - 1;

//Loop through each column and set the DataGridViewAutoSizeColumnMode
//In this case, if we will set the size of all columns automatically, but have
//the last column fill any extra space available.
foreach(DataGridViewColumn column in dataGridView.Columns) 
{
    if (column.Index == columnCount - lastColumnIndex) //Last column will fill extra space
    {
        column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
    }
    else //Any other column will be sized based on the max content size
    {
        column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    }
}

//Turn the scrollbars on for the DataGridView if needed
dataGridView.ScrollBars = ScrollBars.Both;
Run Code Online (Sandbox Code Playgroud)