gpt4 book ai didi

c# - 当列表绑定(bind)到 datagridview 时修复列宽

转载 作者:行者123 更新时间:2023-11-30 22:46:50 25 4
gpt4 key购买 nike

我有一个已绑定(bind)到数据 GridView 的列表。我希望第一列是固定大小。数据绑定(bind)到 dataGridView,我似乎无法找到访问单个列属性的方法。如果我尝试 myDatagridview.colums[0],我会得到一个超出范围的索引,因为它表示列数为 0。

   private DataGridView setUpDataGrid(List<NVRlineVal> _NVRData)
{
//setup dataGridView
DataGridView NVRDataGridView = new System.Windows.Forms.DataGridView();
NVRDataGridView.ColumnHeadersHeightSizeMode =
System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
NVRDataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
NVRDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;


NVRDataGridView.Name = "NVRDataGridView" + nvrIndex;
NVRDataGridView.RowHeadersWidthSizeMode =
System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders;
NVRDataGridView.TabIndex = 0;
NVRDataGridView.DataSource = _NVRData;
//var clmn = NVRDataGridView.Columns[0];

return NVRDataGridView;
}

关于如何仅对其中一列设置固定列宽,其余列将自动调整大小的任何想法?

编辑原始代码,以显示仍然有效的更清晰的版本

最佳答案

我做了类似的事情,但有格式化。

问题是设置数据源后网格没有绘制 - 您需要在 DataBindingComplete 事件中进行更改。

这里有一些片段....

(来自 https://minisqlquery.svn.codeplex.com/svn/trunk/MiniSqlQuery/QueryForm.cs)

-- 网格定义:

        this.gridResults1.AllowUserToAddRows = false;
this.gridResults1.AllowUserToDeleteRows = false;
this.gridResults1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.ColumnHeader;
this.gridResults1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.gridResults1.Dock = System.Windows.Forms.DockStyle.Fill;
this.gridResults1.Location = new System.Drawing.Point(3, 3);
this.gridResults1.Name = "gridResults1";
this.gridResults1.ReadOnly = true;
this.gridResults1.Size = new System.Drawing.Size(1023, 242);
this.gridResults1.TabIndex = 0;

-- 稍后订阅 DataBindingComplete 事件:

grid.DataBindingComplete += GridDataBindingComplete;

-- 处理事件(这里我正在修改格式,但你尝试更改宽度):

    private void GridDataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridView grid = sender as DataGridView;
if (grid == null)
{
return;
}
DataTable dt = grid.DataSource as DataTable;
if (dt == null)
{
return;
}

string nullText = _settings.NullText;
string dateTimeFormat = _settings.DateTimeFormat;

for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Columns[i].DataType == typeof (DateTime))
{
DataGridViewCellStyle dateCellStyle = new DataGridViewCellStyle();
dateCellStyle.NullValue = nullText;
dateCellStyle.Format = dateTimeFormat;
grid.Columns[i].DefaultCellStyle = dateCellStyle;
}
}
}

关于c# - 当列表绑定(bind)到 datagridview 时修复列宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2465770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com