0

我正在尝试更改空文本框的颜色,此表单上有多个文本框,我希望在用户单击提交时突出显示空文本框。在检查所有文本框是否都有值之后,我已经编写了下面的循环,该循环位于我的 btnSubmit 函数中。谁能帮我完成这个循环?

foreach (Control txtbxs in this.Controls)
{
    if (txtbxs is TextBox)
    {
        var TBox = (TextBox)txtbxs;
        if (TBox.Text == string.Empty)
        {
            TBox.ForeColor = Color.Red;
        }
    }

}
lblTopError.Text = "Please fill in the missing billing information";
pnlTopError.Visible = true;
4

4 回答 4

2

如果这是您想要做的,您是否考虑过使用错误提供程序?这将帮助您向用户发出信号并提示他们输入信息。

        errorProvider= new  System.Windows.Forms.ErrorProvider();
        errorProvider.BlinkRate = 1000;
        errorProvider.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.AlwaysBlink;


private void TextValidated(object sender, System.EventArgs e)
    {
       var txtbox = Sender as TextBox;

        if(IsTextValid(txt))
        {
            // Clear the error, if any, in the error provider.
            errorProvider.SetError(txtbox, String.Empty);
        }
        else
        {
            // Set the error if the name is not valid.
            errorProvider.SetError(txtbox, "Please fill in the missing billing information.");
        }
    }
于 2012-11-14T15:44:19.317 回答
2

当您的字符串为空时,更改ForeColor将无济于事,因为您没有 Text 以红色显示。考虑使用BackColor并记住在输入文本时有一个事件将其切换回适当的BackColor.

于 2012-11-14T15:37:33.120 回答
0

You can apply any CSS you want like this:

TBox.Attributes.Add("style", "color: red; border: solid 1px #FC3000")

I would use this instead of:

TBox.ForeColor = Color.Red;
于 2012-11-14T15:41:15.520 回答
0

好吧,因为这种形式的文本框不多,所以我走的是简单的路线,它奏效了,代码如下:

List<TextBox> boxes = new List<TextBox>();
if (string.IsNullOrWhiteSpace(txtFname.Text))
{
    //highlightTextBox= txtFname;
    boxes.Add(txtFname);
}
if (string.IsNullOrWhiteSpace(txtLname.Text))
{
    //highlightTextBox = txtLname;
    boxes.Add(txtLname);
}
if (string.IsNullOrWhiteSpace(txtAddOne.Text))
{
    //highlightTextBox = txtAddOne;
    boxes.Add(txtAddOne);
}
if (string.IsNullOrWhiteSpace(txtTown.Text))
{
    //highlightTextBox = txtTown;
    boxes.Add(txtTown);
}
if (string.IsNullOrWhiteSpace(txtPostCode.Text))
{
    //highlightTextBox = txtPostCode;
    boxes.Add(txtPostCode);
}

foreach (var item in boxes)
{
    if (string.IsNullOrWhiteSpace(item.Text))
    {
        item.BackColor = Color.Azure;
    }
}
lblTopError.Text = "Please fill in the missing billing information highlighted below";
pnlTopError.Visible = true;
于 2012-11-14T16:39:27.140 回答