C# DataGridView,自动计算RowHeaders大小

问题描述 投票:0回答:1

我有一个继承自 DataGrieviw 的自定义 Gridview,并设置了自动 RowHeadersWidthSizeMode。

RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders;

看来 RowHeadersWidth 的最终值不是在构造函数时计算的,而是在稍后(大约在控件加载时)计算的。
在我的应用程序中,自定义控件都根据其大小彼此相邻排列。看来我不能在构造函数中执行此操作,但只能在稍后加载控件之后执行此操作。有没有办法在构造函数中以编程方式强制计算 RowHeadersWidth?
这是我的自定义网格:

    class CustomGridView : DataGridView
    {
        public CustomGridView()
        {
            RowHeadersVisible = false;
            RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders;
            this.RowHeadersWidthChanged += CustomGridView_RowHeadersWidthChanged;
            ScrollBars = ScrollBars.None;
            InitGridView(3);
        }

        public void InitGridView(int numRows)
        {
            this.ColumnCount = 1;
            this.RowCount = numRows;
            for (int row = 0; row < numRows; row++) {
                Rows[row].HeaderCell.Value = "R" + (row+10).ToString();
                Rows[row].Cells[0] = new DataGridViewTextBoxCell();
            }

            Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            this.Height = this.RowCount * this.RowTemplate.Height + 4;
            this.Width = RowHeadersWidth + 45;
            // Unfortunately, RowHeadersWidth does not yet have the final value here at contructor time
        }

        private void CustomGridView_RowHeadersWidthChanged(object sender, EventArgs e)
        {
            // RowHeadersWidth is updated later, around the time the control is loaded
            this.Width = RowHeadersWidth + 45;
        }
    }

这是我的主要形式:

     public partial class Form1 : Form
    {
        private List<CustomGridView> cGridViews = new List<CustomGridView>();
        private int gvWidth1;
        private int gvWidth2;

        private Point GridViewLocation;

        public Form1()
        {
            InitializeComponent();
            GridViewLocation = new Point(10, 10);
            AddCustomGrid(new CustomGridView());
            AddCustomGrid(new CustomGridView());
            gvWidth1 = cGridViews[0].Width;
            this.Load += Form1_Load;
        }

        private void AddCustomGrid (CustomGridView cGridView)
        {
            cGridView.Location = GridViewLocation;
            this.Controls.Add(cGridView);
            cGridViews.Add(cGridView);
            GridViewLocation.X += cGridView.Width + 5;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            // CustomGridView now has the correct size
            gvWidth2 = cGridViews[0].Width;
        }
    }
c# datagridview autosize
1个回答
0
投票

DataGridViewAutoSizeColumnMode.Fill

调整列宽,使所有列的宽度完全一致 填充控件的显示区域。

因此,如果您的 RowHeadersWidth 由此更改,其值取决于您的字体、显示 DPI 和许多其他显示设置。它应该在动态绘制之前计算,因此不能在网格构造函数中计算。

© www.soinside.com 2019 - 2024. All rights reserved.