When a user clicks my Validate Button (in my C#, WinForm, .net 3.5 app) I would like to draw a border around a certain control if it is empty. Say a textbox that is named tbxLastName I thought I needed to do something like this -->
ControlPaint.DrawBorder(Graphics.FromHwnd(this.Handle),
tbxLastName.ClientRectangle, Color.Firebrick, ButtonBorderStyle.Solid);
Unfortunately, I have no idea what to put for the Graphics Object as what I have does NOTHING.
All of the examples I have come across, MSDN - HERE, have this code in a Paint Event. Like so -->
private void panel1_Paint(object sender, PaintEventArgs e)
{
ControlPaint.DrawBorder(e.Graphics, this.panel1.ClientRectangle,
Color.DarkBlue, ButtonBorderStyle.Solid);
}
I, however, only want to have the border appear while certain conditions are meet which is kicked off by a Button_Click
So many of the suggestions suggest using a container object to hold the textbox and call it's Paint_Event. I did this and a box appears but NOT around the control. It appears in the Top Left corner of the Container Control. Here is what I am doing -->
private void grpImmunizationCntrl_Paint(object sender, PaintEventArgs e)
{
if (lkuNOImmunizationReason.Text.Equals(string.Empty)
{
ControlPaint.DrawBorder(
e.Graphics, lkuNOImmunizationReason.ClientRectangle,
Color.Firebrick, ButtonBorderStyle.Solid);
}
}
EDIT
This is what I came up with combining suggestions here with what worked for me.
public static void HighlightRequiredFields(Control container, Graphics graphics, Boolean isVisible)
{
Rectangle rect = default(Rectangle);
foreach (Control control in container.Controls)
{
if (control.Tag is string && control.Tag.ToString() == "required")
{
rect = control.Bounds;
rect.Inflate(3, 3);
if (isVisible && control.Text.Equals(string.Empty))
{
ControlPaint.DrawBorder(graphics, rect, Color.FromArgb(173,216,230), ButtonBorderStyle.Solid);
}
else
{
ControlPaint.DrawBorder(graphics, rect, container.BackColor, ButtonBorderStyle.None);
}
}
if (control.HasChildren)
{
foreach (Control ctrl in control.Controls)
{
HighlightRequiredFields(ctrl, graphics, isVisible);
}
}
}
}
I call this from the Paint_Event
of any Container I need to.