I am wondering if there is a way to create templates for controls and apply them to only certain controls. The function below makes predefined setting for controls(GridView and Listbox) and apply it to the controls found in the main Form. The Problems are:
- It doesn’t work to controls in other forms.
- I can’t specify to which controls it applies.
I’m sure there is a better way but i guess my googling is worse than my programming skill.
public void SettingControls()
{
List<Control> lstControls = GetAllControls(this.Controls);
//DataGridView
DataGridViewCellStyle style;
style = new DataGridViewCellStyle();
style.Alignment = System.Windows.Forms.DataGridViewContentAlignment.BottomCenter;
style.BackColor = System.Drawing.Color.GhostWhite;
style.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
style.ForeColor = System.Drawing.Color.Black;
style.SelectionBackColor = System.Drawing.SystemColors.Highlight;
style.SelectionForeColor = System.Drawing.Color.Navy;
style.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
DataGridViewAdvancedBorderStyle borderStyle;
borderStyle = new DataGridViewAdvancedBorderStyle();
borderStyle.Bottom = DataGridViewAdvancedCellBorderStyle.OutsetDouble;
foreach (Control control in lstControls)
{
//DataGridView
if (control is DataGridView)
{
DataGridView dgv = ((DataGridView)control);
dgv.Dock = DockStyle.Fill;
dgv.AutoGenerateColumns = true;
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
dgv.Dock = DockStyle.Fill;
dgv.DefaultCellStyle.BackColor = Color.Bisque;
dgv.BorderStyle = BorderStyle.FixedSingle;
dgv.BackgroundColor = Color.GhostWhite;
dgv.DefaultCellStyle = style;
}
//ListBox
if (control is ListBox)
{
ListBox lb = ((ListBox)control);
lb.MeasureItem += new MeasureItemEventHandler(lb_MeasureItem);
lb.DrawItem += new DrawItemEventHandler(lb_DrawItem);
}
}
}
The easiest approach would be to create a base form that your other forms inherit from and then add the method above as a standard method that is called in the Form_Load event, for example.
For example: