Andreas Ahlen

Andreas Ahlen

  • NA
  • 145
  • 72.2k

Focus Color on Textbox controls

Aug 31 2010 8:54 AM
Anyone a better idea how to use the focus event of Textbox controls to set the Textbox Backgroundcolor according to Enter() and Leave() events. I even implemented an Error color advise.

The normal backgroud color of the TextBox control is System.Drawing.Color.White, the focused color is System.Drawing.Color.Yellow and the error sign color is System.Drawing.Color.Red.

The implemented function is called by every Textbox control when occuring Enter and Leave events and setting the appropriate color. Then a Button1 event simulates an error (e.s.: invalid value, unknown username, text not found, etc.)

The Button2 Click-Event simulates to pass a non textbox object to the TextBox_Enter (Enter event in tetxBox1)




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace tboxfocus
{
public partial class Form1 : Form
{
private System.Drawing.Color m_tbcolorenter = System.Drawing.Color.Yellow;
private System.Drawing.Color m_tbcolorleave = System.Drawing.Color.White;
private System.Drawing.Color m_tbcolorerror = System.Drawing.Color.Red;
private Boolean m_tbcolorerrorflag = false;

private void ThrowErrormessage(object sender)
{
if (sender != null)
MessageBox.Show(String.Concat("Invalid object: ", sender.ToString(),
", Only Textbox objects are allowed!"), "Error - invalid object!");
else
MessageBox.Show("Unknown error", "Sorru :=(");
}


public Form1()
{
InitializeComponent();
}

private void textBox1_TextChanged(object sender, EventArgs e)
{

}

private void textBox2_TextChanged(object sender, EventArgs e)
{

}

private void Form1_Load(object sender, EventArgs e)
{

}

private void TextBox_Enter(object sender, EventArgs e)
{
TextBox tb = null;
if (sender is TextBox)
{
tb = (TextBox)sender;
if (m_tbcolorerrorflag)
tb.BackColor = m_tbcolorerror;
else
tb.BackColor = m_tbcolorenter;
}
else ThrowErrormessage(sender);
return;

}

private void TextBox_Leave(object sender, EventArgs e)
{
TextBox tb = null;
if (sender is TextBox)
{
tb = (TextBox)sender;
tb.BackColor = m_tbcolorleave;
}
else ThrowErrormessage(sender);
return;
}

private void TextBox_Error(object sender, EventArgs e)
{
TextBox tb = null;
if (sender is TextBox)
{
tb = (TextBox)sender;
tb.BackColor = m_tbcolorerror;
tb.Focus();
m_tbcolorerrorflag = false;
}
else ThrowErrormessage(sender);
return;
}

private void button1_Click(object sender, EventArgs e)
{
m_tbcolorerrorflag = true;
TextBox_Error(textBox1, e);
}

private void button2_Click(object sender, EventArgs e)
{
TextBox_Enter(button2, e);
}


}
}
Regards
Andy
// Edit: error in post fixed (White, White instead of White, Yellow, bold, italic font types and colors added, button2 description)


Attachment: tboxfocus.zip

Answers (2)