I'm creating a winforms app using VS 2022 and getting the above error.
Checking MSDN there is no Control property called BorderStyle
. Instead BorderStyle
documentation is found under Windows Desktop 6.
This is my code:
using System.Drawing;
using System.Windows.Forms;
namespace BURS_Library
{
public class Styles : Form
{
public static void LBLasBTN_Enable(Control ctrlName)
{
ctrlName.BackColor = Color.FromArgb(214, 206, 165);
ctrlName.ForeColor = Color.FromArgb(0, 0, 0);
ctrlName.BorderStyle = BorderStyle.FixedSingle;
ctrlName.Font = new Font("Segoe UI", 8, FontStyle.Bold);
ctrlName.Enabled = true;
ctrlName.Cursor = Cursors.Hand;
}
All of the other properties are compiling. Looking in the Designer file I find "controlName".BorderStyle = etc so I was surprised when this didn't work. What should I be using instead of Control
?
Thank you.
CodePudding user response:
A WinForm Control
is just a common base class for all WinForm controls: read the docs. Not all WinForm controls have a border/border style.
There are a couple of options if you want to set the border style with a generic method.
Reflection
Using reflection is basically a catch-all here and will only set the border style if a border style property exists:
public static void LBLasBTN_Enable( Control ctrl )
{
ctrl.BackColor = Color.FromArgb( 214, 206, 165 );
ctrl.ForeColor = Color.FromArgb( 0, 0, 0 );
ctrl.Font = new Font( "Segoe UI", 8, FontStyle.Bold );
ctrl.Enabled = true;
ctrl.Cursor = Cursors.Hand;
PropertyInfo pi = ctrl.GetType().GetProperty( "BorderStyle", BindingFlags.Public | BindingFlags.Instance );
if( pi != null )
{
pi.SetValue( ctrl, BorderStyle.FixedSingle );
}
}
Casting
Alternatively, the control can be cast into whatever type you expect to have a border style:
public static void LBLasBTN_Enable( Control ctrl )
{
ctrl.BackColor = Color.FromArgb( 214, 206, 165 );
ctrl.ForeColor = Color.FromArgb( 0, 0, 0 );
ctrl.Font = new Font( "Segoe UI", 8, FontStyle.Bold );
ctrl.Enabled = true;
ctrl.Cursor = Cursors.Hand;
if( ctrl is Label lbl )
{
lbl.BorderStyle = BorderStyle.FixedSingle;
}
// add other types as needed...
}
Personally I'm a bit lazy and would just go the reflection route. However, if you want to be fully explicit, then go the casting route.