如何自动调整窗体以使其控件不具有滚动条

时间:2018-02-04 12:50:39

标签: c# winforms c#-4.0

我有一个Form,它只包含一个停靠填充的DataGridView。 DataGridView只有一列,行可以很多。

我只有一小部分数据可供展示。 以下是一个示例数据:

enter image description here

我希望表单自动调整其高度,以便不显示垂直滚动条。

这是我的代码:

    public RowDetailsForm(DataGridViewRow row, DataGridViewColumnCollection cols, int localizationFoldersCount)
    {
        InitializeComponent();
        this.row = row;
        this.cols = cols;
        this.localizationFoldersCount = localizationFoldersCount;
        CreateDetails();
    }

    private void CreateDetails()
    {
        detailDataGridView.Rows.Add(row.Cells["keyColumn"].Value.ToString());
        detailDataGridView.Rows[detailDataGridView.Rows.Count - 1].HeaderCell.Value = "Translation Key";

        foreach (DataGridViewCell cell in row.Cells)
        {
            if (cell.ColumnIndex != 0 && cell.Value != null)
            {
                string cellText = cell.Value.ToString();
                string rowHeaderText = cols[cell.ColumnIndex].HeaderText;
                if (cellText != "" && cols.Count - localizationFoldersCount <= cell.ColumnIndex)
                {
                    cellText = cellText.Substring(1, cellText.Length - 2).Replace("][", Environment.NewLine);

                    string pattern = Environment.NewLine;
                    MatchCollection matches = Regex.Matches(cellText, pattern);
                    rowHeaderText += "(" + (matches.Count + 1) + ")";
                }
                detailDataGridView.Rows.Add(cellText);
                detailDataGridView.Rows[detailDataGridView.Rows.Count - 1].HeaderCell.Value = rowHeaderText;
            }
        }            
    }        

这是如何编码的?

1 个答案:

答案 0 :(得分:0)

您需要准确测量表单高度所需的像素数量才能在表单中包含detailDataGridView
您必须在设置行数后执行此操作,在该示例中form将自己适应datagridview高度,滚动条将是不必要的。
请在示例中阅读我的评论:

private void ResizeDgv()
{
    detailDataGridView.AllowUserToAddRows = false;
    // discover max form (screen) height.
   var maxHeight = Screen.PrimaryScreen.WorkingArea.Height;
    // discover forms title height
    Rectangle screenrectange = this.RectangleToScreen(this.ClientRectangle);
    var titleheight = screenrectange.Top - this.Top;
    // discover datagridview columns height
    var colHeight = detailDataGridView.Columns[0].HeaderCell.Size.Height;
    // discover total rows height
    var totalRowsHeight = detailDataGridView.RowCount * detailDataGridView.Rows[0].HeaderCell.Size.Height;
    // discover borders height
    var borders = System.Windows.Forms.SystemInformation.FrameBorderSize.Height * 3;
    // total height needed
    var total = totalRowsHeight + colHeight + titleheight + borders;

    if (total > maxHeight)
    {
        // extreme case: There is no way to avoid scrollbar - max screen hight is less the datagridview calculated height
        this.Size = new Size(this.Width, maxHeight);
    }
    else
    {
        // resize forms height according to total height
        this.Size = new Size(this.Width, total);
    }
}
相关问题