让我们说我想在DataGridViewColumn
等类中添加属性。
有没有这样做的方法,我可以把这些对象转换成让我们说DataGridViewCheckBoxColumn
这是我正在做的但却给我一个错误。
我有自己的班级DataGridViewColumn
Public Class DataGridViewColumn
Inherits System.Windows.Forms.DataGridViewColumn
Private Field As String
Public Property SomeField() As String
Get
Return Field
End Get
Set(ByVal value As String)
Field = value
End Set
End Property
End Class
哪个好,按我想要的方式工作。但是,当我去尝试这样的事情......它不喜欢它
Private Function gen(name As String) As DataGridViewColumn
Select Case name
Case "DataGridViewTextBoxColumn"
Dim c2 As New DataGridViewTextBoxColumn
c2.Name = "tstColumn"
c2.HeaderText = "Test Column"
c2.ReadOnly = False
Return c2
End Select
Return Nothing
End Function
有什么办法可以让我这样做吗?我也试过制作一个DataGridViewTextBoxColumn
类,然后加入System.Windows.Forms.DataGridViewTextBoxColumn
但似乎没什么用。
错误只是说即使我拥有自己的DataGridViewTextBoxColumn也无法转换为类型DataGridViewColumn
答案 0 :(得分:2)
我认为无论如何,我都会在评论中提供答案。如果你只想要一个"属性"然后你可以这样做:
Imports System.Runtime.CompilerServices
Namespace YourBusinessName.Windows.Forms
Public Module DataGridViewColumnExtensions
<Extension>
Public Function GetField(source As DataGridViewColumn) As String
Return TryCast(source.Tag, String)
End Function
<Extension>
Public Sub SetField(source As DataGridViewColumn, value As String)
source.Tag = value
End Sub
End Module
End Namespace
然后你可以使用这样的方法:
Imports YourBusinessName.Windows.Forms
'...
Me.Column1.SetField("Hello World")
Dim fieldValue = Me.Column1.GetField()
如果你想要多个&#34;属性&#34;然后你可以用Dictionary
:
Imports System.Runtime.CompilerServices
Namespace YourBusinessName.Windows.Forms
Public Module DataGridViewColumnExtensions
<Extension>
Public Function GetField1(source As DataGridViewColumn) As String
Return GetField(source, "Field1")
End Function
<Extension>
Public Function GetField2(source As DataGridViewColumn) As String
Return GetField(source, "Field2")
End Function
Private Function GetField(source As DataGridViewColumn, propertyName As String) As String
Dim fields = TryCast(source.Tag, Dictionary(Of String, Object))
If fields Is Nothing OrElse Not fields.ContainsKey(propertyName) Then
Return Nothing
End If
Return TryCast(fields(propertyName), String)
End Function
<Extension>
Public Sub SetField1(source As DataGridViewColumn, value As String)
SetField(source, "Field1", value)
End Sub
<Extension>
Public Sub SetField2(source As DataGridViewColumn, value As String)
SetField(source, "Field2", value)
End Sub
Private Sub SetField(source As DataGridViewColumn, propertyName As String, value As String)
Dim fields = TryCast(source.Tag, Dictionary(Of String, Object))
If fields Is Nothing Then
fields = New Dictionary(Of String, Object)
source.Tag = fields
End If
fields(propertyName) = value
End Sub
End Module
End Namespace
您仍然会以相同的方式使用这些方法:
Imports YourBusinessName.Windows.Forms
'...
Me.Column1.SetField1("Hello World")
Dim fieldValue = Me.Column1.GetField2()
请注意,可以在DataGridViewColumn
的任何类型的对象上调用扩展DataGridViewColumn
类的方法。