我有一个继承自 DataGrieviw 的自定义 Gridview,并设置了自动 RowHeadersWidthSizeMode。
RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders;
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;
}
}
DataGridViewAutoSizeColumnMode.Fill:
调整列宽,使所有列的宽度完全一致 填充控件的显示区域。
因此,如果您的 RowHeadersWidth 由此更改,其值取决于您的字体、显示 DPI 和许多其他显示设置。它应该在动态绘制之前计算,因此不能在网格构造函数中计算。