VB.NET自定义DataGridView控件 - 运行时重复列?

时间:2016-05-28 13:34:25

标签: c# vb.net visual-studio datagridview

我正在创建一个继承自DataGridView的控件。我在控件构造函数中以编程方式添加列,就像这样。

Public Sub New()
    MyBase.New()

'This call is required by the Component Designer.
InitializeComponent()

OptionsForm = New frmOptions(Me)

'NOTE: Add columns programmatically rather than via the designers properties window, or they will be duplicated when added to a form!
Dim colIpAddress, colPort, colStatus, colSpeed, colCountry As New DataGridViewTextBoxColumn
    colIpAddress.HeaderText = "IP"
    colPort.HeaderText = "Port"
    colStatus.HeaderText = "Status"
    colSpeed.HeaderText = "Speed"
    colCountry.HeaderText = "Country"

    Columns.AddRange({colIpAddress, colPort, colStatus, colSpeed, colCountry})

    RowCount = 1
Me.Refresh()
End Sub

当我将控件添加到表单时,它会正确显示列。但是在运行时期间,列是重复的。我添加了一个if语句,这样只有当前列数为0时才会添加列,但仍无济于事。

任何人都知道最近发生了什么?谢谢! :)

2 个答案:

答案 0 :(得分:0)

AutoGenerateColumns控件上的DataGridView属性设置为false:

dataGridView1.AutoGenerateColumns = false;

答案 1 :(得分:0)

通过在添加列之前添加检查来修复此问题,并且仅在设计模式下添加它们。我想我明白为什么现在这样。

Public Sub New()
    MyBase.New()

'This call is required by the Component Designer.
InitializeComponent()

If Me.DesignMode Then
    OptionsForm = New frmOptions(Me)
    AutoGenerateColumns = False
    'NOTE: Add columns programmatically rather than via the designers properties window, or they will be duplicated when added to a form!
    Dim colIpAddress, colPort, colStatus, colSpeed, colCountry As New DataGridViewTextBoxColumn
    colIpAddress.HeaderText = "IP"
    colPort.HeaderText = "Port"
    colStatus.HeaderText = "Status"
    colSpeed.HeaderText = "Speed"
    colCountry.HeaderText = "Country"

    Columns.AddRange({colIpAddress, colPort, colStatus, colSpeed, colCountry})

    RowCount = 1
    Me.Refresh()
End If

End Sub

希望这可以在AutoGenerateColumns = False无效时帮助某人。