【发布时间】:2016-04-08 14:10:22
【问题描述】:
我制作了一个自定义的 DataGridView 组件,里面有一个标准的 DataGridViewImageColumn。当我不需要在特定表中时,新属性会更改列的可见性。我在构造函数中添加列并在 CellFormatting 事件上更新它。这就是按预期工作的部分。
当我将控件放到一个新表单上时,它会显示其中的新列。运行程序会在网格中生成两个图像列。
一个新的表单刚刚添加了组件并设置了Dock.Fill
当我在不更改任何内容的情况下启动它时,它会显示两列。第一个工作正常,第二个总是显示丢失的 x 图像(其中没有数据,所以它们都显示 x)。
在表单的设计器中有一个自动添加的图像列。
private CustomDataGridView customDataGridView1;
private System.Windows.Forms.DataGridViewImageColumn dataGridViewImageColumn1;
当我继续编辑表单时,有时 VS 会创建更多相同列的副本。要解决这个问题,我必须不时清除 DGV.Columns 列表。
如何防止 VS 复制我的字段?
以下代码是重现问题的最小部分。
public class CustomDataGridView : DataGridView
{
private DataGridViewImageColumn EditStatusIcons;
private bool hasIcons = true;
public bool HasIcons
{
get { return this.hasIcons; }
set
{
if (this.Columns["EditIcons"] == null) return;
this.Columns["EditIcons"].Visible = value;
this.hasIcons = value;
}
}
public CustomDataGridView()
{
this.EditStatusIcons = new System.Windows.Forms.DataGridViewImageColumn();
this.EditStatusIcons.HeaderText = "";
this.EditStatusIcons.Name = "EditStatusIcons";
this.Columns.Add(this.EditStatusIcons);
}
}
编辑:我也尝试使用this.AutoGenerateColumns = false; 就像Custom DataGridView adds columns everytime I build 中所说的那样。没有任何变化。
清除表单上列出的列会删除工作列并留下一个列 dataGridViewImageColumn1,它只是一个名称错误的完整空列。
【问题讨论】:
-
你在datagridview的设计器中添加了多少列?
-
无。我只是将组件放在表单上并将 Dock 样式设置为 Fill。 VS 自己添加了列。
-
控件按预期运行。您在构造函数中添加了一列,然后设计器序列化该列。然后运行应用程序,它在构造函数中添加一列。所以你有2列。并且以这种方式继续下去,并且不限于 2 列。即使您不需要构建和运行,打开包含网格的表单并在表单中进行一些小的更改并保存就足够了。一个新的专栏诞生了!
标签: c# .net winforms datagridview windows-forms-designer