Saturday, September 13, 2008

Change ForeColor of a TextBox control

When we disable a TextBox, we can change its BackColor but if we change the ForeColor, it doesn't apply. To solve the problem, I created a new class based on TextBox and changed the OnPaint method to do the ob for me:

- Add a new class to your solution
- Define your new class based on TextBox
public class MyTextBox : TextBox
{
public MyTextBox()
{
this.SetStyle(ControlStyles.UserPaint, true);
}

protected override void OnPaint(PaintEventArgs e)
{
SolidBrush myDrwBrush = new SolidBrush(Color.Black);
e.Graphics.DrawString(this.Text, this.Font, myDrwBrush, 0F, 0F);
}
}
- Instantiate an object from the new class on your form
- Customize its properties
- Add it to your form controls like this:
MyTextBox myTxtBox = new MyTextBox();
myTxtBox.Location = new System.Drawing.Point(12, 36);
myTxtBox.Name = "myTxtBox";
myTxtBox.Size = new System.Drawing.Size(260, 20);
myTxtBox.Text = "This is a test text box";
this.Controls.Add(myTxtBox);
- Disable it in your code to see the effect:
this.Controls["myTxtBox"].Enabled = false
In addition, I found another similar solution in the following URL:
http://austinleng.spaces.live.com/Blog/cns!6F894DC66A2F0AFF!454.entry

Share/Bookmark

No comments: