2017-09-19 26 views
0

我有一个C#中的Windows窗体应用程序的datagridview对象。用户可以添加一些行,但限于任何数字,因此用户不能输入太多的行。如何将所有行放入datagridview中,使垂直滚动条不出现C#?

我要让自动调整大小,使他们能够适应的DataGridView和垂直滚动条将不会出现在所有行(行高和字体大小)。有什么建议么?

感谢,

回答

0

太感谢你了圣剑,你的答案真的帮我解决这个问题!它的一些部分不适合我,所以我改变了它们。我发现字体大小和行高有关系;我发现三种不同行高的三种最佳字体大小,并进行回归以找到特定行高的最佳字体大小。

private void ResizeRows() 
    { 
     // Get the height of the header row of the DataGridView 
     int headerHeight = this.dataGridView1.ColumnHeadersHeight; 

     // Calculate the available space for the other rows 
     int availableHeight = this.dataGridView1.Height - headerHeight; 

     float rowSize = (float)availableHeight/(float)this.dataGridView1.Rows.Count; 

     float fontSize = 0.8367F * rowSize - 3.878F; 

     // Resize each row in the DataGridView 
     foreach (DataGridViewRow row in this.dataGridView1.Rows) 
     { 
      row.Height = (int)rowSize; 
      row.DefaultCellStyle.Font= new Font(dataGridView1.Font.FontFamily, fontSize, GraphicsUnit.Pixel); 
     } 
    } 
0

你可以计算每行的可用空间,然后调整他们都:

private void ResizeRows() 
{ 
    // Calculate the font size 
    float fontSize = calculateFontSize(); 

    // Resize the font of the DataGridView 
    this.dataGridView1.Font = new Font(this.dataGridView1.Font.FontFamily, fontSize); 

    // Get the height of the header row of the DataGridView 
    int headerHeight = this.dataGridView1.Columns[0].Height; 

    // Calculate the available space for the other rows 
    int availableHeight = this.dataGridView1.Height - headerHeight - 2; 

    float rowSize = (float)availableHeight/(float)this.dataGridView1.Rows.Count; 

    // Resize each row in the DataGridView 
    foreach (DataGridViewRow row in this.dataGridView1.Rows) 
    { 
     row.Height = (int)rowSize; 
    } 
} 

你可以在你的两个DataGridView中的事件添加一个调用这个方法:

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) 
    { 
     this.ResizeRows(); 
    } 

    private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) 
    { 
     this.ResizeRows(); 
    } 

这样,你的DataGridView应该每行添加或删除的时间调整其行。你可以用不同的字体大小实验方法calculateFontSize

相关问题