簡體   English   中英

c#如何更改特定文本框的顏色為空?

[英]c# How do i change the color of a specific textbox if it is empty?

我正在嘗試更改一個空文本框的顏色,此表單上有多個文本框,當用戶單擊“提交”時,我希望突出顯示該空文本框。 在檢查所有文本框是否都有值之后,我在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;

當您的字符串為空時,更改ForeColor不會執行任何操作,因為您沒有將文本顯示為紅色。 考慮使用BackColor並記住在輸入文本時將其切換回適當的BackColor時發生事件。

如果這是您要嘗試的操作,您是否考慮過使用錯誤提供程序? 這將幫助您向用戶發出信號並提示他們輸入信息。

        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.");
        }
    }

您可以像這樣應用任何CSS:

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

我會用它代替:

TBox.ForeColor = Color.Red;

好吧,因為這種形式的文本框很少,所以我走了一條簡單的路線,它成功了,代碼如下:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM