2017-09-19 29 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

相關問題