簡體   English   中英

如何將所有行放入datagridview中,以使垂直滾動條不出現C#?

[英]How to fit all rows into datagridview so vertical scroll bar doesn't appear C#?

我在C#中有一個Windows表格應用程序的datagridview對象。 用戶可以添加一些行,但是此行數可以限制為任何數量,因此用戶不能輸入太多行。

我想使所有行(行高和字體大小)自動調整大小,以便它們可以適合datagridview,並且不會出現垂直滾動條。 有什么建議么?

謝謝,

您可以計算每行的可用空間,然后調整所有大小:

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嘗試使用不同的字體大小

非常感謝Seiken,您的回答確實幫助我解決了問題! 它的某些部分對我不起作用,所以我更改了它們。 我發現字體大小和行高之間存在聯系。 我找到了三個不同行高的三個最佳字體大小,並進行了回歸以找到特定行高的最佳字體大小。

 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);
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM