【问题标题】:How to set the margins of text box red if error is present如果存在错误,如何将文本框的边距设置为红色
【发布时间】:2017-08-18 16:22:13
【问题描述】:

我只是想知道是否可以轻松地将文本框的边距设置为特定颜色?我使用winforms,在我的验证事件处理程序中我有一系列error providers,如果返回false,我只想将边距设置为红色,如果成功则为绿色。如果没有隐藏任何控件,这可能吗?我知道如何设置前景和面板颜色,但将这一切都隐藏在它后面似乎太草率了。这是我的验证事件处理程序。

       private void txt_LndLine_Validating(object sender, CancelEventArgs e)
        {

            if (utility.isNum,(txt_LndLine.Text))
            {
                epLandline.SetError(txt_LndLine, "Please use unknown Entity!!!");

                return;
            }

            else 
            {
                epLandline.Clear();
                _IsValid = true;

            } 
        }

只是一个查询,因为 event hadnler 工作正常,只是不会介意以更智能的方式呈现错误而不是图标

【问题讨论】:

标签: c# .net winforms


【解决方案1】:

这是一个替代解决方案,它不会添加任何额外的控件。它将边框绘制到TextBoxes'Parent

通过将例程挂钩到您的TextBoxParentPaint 事件一次来设置它,可能是这样的:

textBox1.Parent.Paint += DrawMargins;

现在您可以设置Tag 来保存您要使用的Brush

textBox1.Tag = Brushes.Red;
textBox2.Tag = Brushes.Green;

更改Brush后需要触发例程,通过InvalidatingParent:

textBox1.Parent.Invalidate();

要将TextBox 从画中取出,请将Tag 重置为null

textBox1.Tag = null;

当然,您也可以取消挂钩整个事件:

textBox1.Parent.Paint -= DrawMargins;

绘制方法如下:

private void DrawMargins(object sender, PaintEventArgs e)
{
    Control parent = sender as Control;
    foreach ( Control ctl in parent.Controls)
    { 
        SolidBrush brush = ctl.Tag as SolidBrush;
        if (brush == null) continue;
        e.Graphics.FillRectangle(brush, ctl.Left - ctl.Margin.Left,
            ctl.Top - ctl.Margin.Top,
            ctl.Width + ctl.Margin.Horizontal,
            ctl.Height + ctl.Margin.Vertical);
    }
}

请注意,这适用于在Tag 中具有SolidBrush 并且是相同 父级的子级的任何控件。如果某些控件是嵌套的,比如在 Panel 或 GroupBox 中,我猜你应该用参与控件的 List<Control> 替换 parent.Controls 集合上的循环..

我已经放大了第一个TextBox的左边距,你可以看到..

【讨论】:

    【解决方案2】:

    cmets 中的答案可能是一个很好的答案 (@RudyTheHunter)。

    我有一个简单的方法。

    text box 正下方放置一个panel 控件并更改面板的边框颜色。

    我试过了,如下图所示。

    代码:

                if (utility.isNum,(txt_LndLine.Text))
                {
                    epLandline.SetError(txt_LndLine, "Please use unknown Entity!!!");
                  //PANEL COLOR
                  this.panel1.BackColor = System.Drawing.Color.Green;
                  this.panel1.Padding = new System.Windows.Forms.Padding(5);
    
                    return;
                }
    
                else 
                {
                    epLandline.Clear();
    
                   //PANEL COLOR
                    this.panel1.BackColor = System.Drawing.Color.Red;
                    this.panel1.Padding = new System.Windows.Forms.Padding(5);
    
                    _IsValid = true;    
                } 
    

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 2013-04-17
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      相关资源
      最近更新 更多