I'm writing a custom DataGridView object for a large project to hand out to a bunch of developers to make our app sections look consistent.
I want to set defaults for many of the properties of the DataGridView, and I can set many of them like this:
<System.ComponentModel.Browsable(True), System.ComponentModel.DefaultValue(DataGridViewAutoSizeColumnsMode.Fill)>_
Public Overloads Property AutoSizeColumnsMode() As DataGridViewAutoSizeColumnMode
Get
Return MyBase.AutoSizeColumnsMode
End Get
Set(ByVal value As DataGridViewAutoSizeColumnMode)
MyBase.AutoSizeColumnsMode = value
End Set
End Property
These properties overload with their defaults just fine. Its when I started trying to make default Cell styles that I ran into the issue. Since the DataGridViewCellStyle is a class, I cannot make a constant out of it. I've tried changing all of the settings to what I want them to be in the class constructor, and that works great, except that changes made in the designer properties just get set back as soon as the app runs. So putting the changes in the constructor won't do.
Is there anywhere else I can put code that only runs when the control is first dropped on the designer? or any other way of setting a default?
Actually, I thought about it a while longer and came across a simpler solution for my issue. This does not work for all cases because it relies on the fact that the person using the custom component will likely never want to revert an entire CellStyle back to windows defaults. I ended up comparing a new CellStyle to the current one in the constructor, and only setting the style if they matched. This way it won't overwrite changes, but it will set it up the first time.
Public Class CustomDataGridView
Inherits System.Windows.Forms.DataGridView
Private RowStyle As New DataGridViewCellStyle
Public Sub New()
RowStyle.BackColor = Color.FromArgb(223, 220, 200)
RowStyle.Font = New Font("Arial", 12.75, FontStyle.Bold, GraphicsUnit.Point)
RowStyle.ForeColor = Color.Black
RowStyle.SelectionBackColor = Color.FromArgb(94, 136, 161)
If MyBase.RowsDefaultCellStyle.ToString = (New DataGridViewCellStyle).ToString Then
MyBase.RowsDefaultCellStyle = RowStyle
End If
End Sub
End Class
Just goes to show, Just because you have a golden hammer, doesn't mean that every problem is a nail.