我在名为Validators
的类中为我的文本框使用验证方法。我还试图在文本框上绘制一个无法验证的矩形。
我正在使用此代码:
private void TextBoxStyle(TextBox textBox)
{
Graphics graphics = textBox.CreateGraphics();
Pen redPen = new Pen(Color.Red);
graphics.DrawRectangle(redPen, textBox.Location.X, textBox.Location.Y, textBox.Width, textBox.Height);
}
/// <summary>
/// Validates TextBoxes for string input.
/// </summary>
public bool ValidateTextBoxes(params TextBox[] textBoxes)
{
foreach (var textBox in textBoxes)
{
if (textBox.Text.Equals(""))
{
Graphics graphics = textBox.CreateGraphics();
Pen redPen = new Pen(Color.Red);
graphics.DrawRectangle(redPen, textBox.Location.X, textBox.Location.Y, textBox.Width, textBox.Height);
return false;
}
}
return true;
}
问题是......矩形不会显示。我做错了代码吗?如果是,请帮忙。
答案 0 :(得分:3)
我看到几个潜在的问题:
Graphics
对象,但使用表单中的文本框偏移量来进行绘图。最终结果:矩形在文本框的可见区域之外翻译。尝试使用位置(0,0)
。当你在check out ErrorProvider
课时。它可能只是满足您现成的需求。
答案 1 :(得分:1)
编写用户控件
public partial class UserControl1 : UserControl
{
private string text;
private bool isvalid = true;
public string Text
{
get { return textBox.Text; }
set { textBox.Text = value; }
}
public bool isValid
{
set
{
isvalid = value;
this.Refresh();
}
}
TextBox textBox = new TextBox();
public UserControl1()
{
InitializeComponent();
this.Paint += new PaintEventHandler(UserControl1_Paint);
this.Resize += new EventHandler(UserControl1_Resize);
textBox.Multiline = true;
textBox.BorderStyle = BorderStyle.None;
this.Controls.Add(textBox);
}
private void UserControl1_Resize(object sender, EventArgs e)
{
textBox.Size = new Size(this.Width - 3, this.Height - 2);
textBox.Location = new Point(2, 1);
}
private void UserControl1_Paint(object sender, PaintEventArgs e)
{
if (isvalid)
ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, Color.Black, ButtonBorderStyle.Solid);
else
ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);
}
}
更新: 刚刚添加了isvalid属性
你可以放置属性来显示边框。如果输入有效则显示正常边框,如果控制输入无效则显示红色边框。
答案 2 :(得分:1)
一旦TextBox控件以某种方式失效,直接绘制到TextBox上的任何内容都将消失。
正确的方法是向项目添加用户控件并在其画布上添加TextBox。在它周围留一点边框。
现在,您可以在需要时简单地为用户控件的画布红色背景着色,它看起来就像是围绕TextBox绘制的边框。
您可以直接向用户控件添加代码,以便在文本更改时对其进行验证。这样,您只需编写一次代码,只需在表单或页面中添加所需数量的TextBox即可。
答案 3 :(得分:0)
你不应该只是从某个地方画一个控件。绘画的构建将在下一次重写它。 Control有一个paint绘制事件你应该绘画。只要需要绘画,就会使用它。
在你的validate方法中,你应该只在某个地方存储验证的结果,以便它可以在paint事件中使用并调用Invalidate()以便强制重新绘制。
答案 4 :(得分:0)
// You may use this
Label lblHighlight = new Label ();
Rectangle rc = new Rectangle(this.Left - 2, this.Top - 2, this.Width + 4, this.Bottom - this.Top + 4);
this.Parent.Controls.Add(lblHighlight);
lblHighlight.Bounds = rc;
lblHighlight.BackColor = "Red";