我如何在asp红色中打开标签

时间:2011-08-10 15:12:05

标签: c# asp.net

嗨,当用户在文本框中输入错误的答案时,我想在.aspx中将标签变为红色。

但不知道怎么样,我能做到吗?

5 个答案:

答案 0 :(得分:2)

您可以使用javascript(从文本框的onchange调用此代码)来执行此操作:

<label for="myTextBox" id="myLabel">For my textbox</label>
<input id="myTextBox" onchange="ValidateAnswer();">

function ValidateAnswer() {
    var txtBox = document.getElementById('myTextBox');
    if(txtBox.value != "answer") {
       document.getElementById('myLabel').style.color = 'red';
    }
}

如果您使用的是ASP.Net,也可以使用Validator控件:

<asp:CustomValidator runat="server" ID="cvAnswer"
    ControlToValidate="myTextBox"
    ErrorMessage="required"
    ClientValidationFunction="ValidateAnswer"
    ValidateEmptyText="true"
    Display="Dynamic"
    ValidationGroup="First"
    ForeColor="red" >
</asp:CustomValidator>

function ValidateAnswer(sender, args) {
  args.IsValid = args.Value != "" && args.Value == "answer here";
  if(!args.IsValid) {
     document.getElementById('myLabel').style.color = 'red';
  }
  return;   
}

答案 1 :(得分:1)

从服务器端代码:

  if(this.txtBox.Text.Length == 0) 
      {
        //no value entered
        lblMyLabel.BackColor = Color.Red;
        lblMyLabel.Text = "Invalid entry";
      }

客户方可以这样做:

标记:

 <asp:TextBox onchange="Validate();" runat="server" id="myTextBox"/>

JS:

function Validate()
 {
  var t = document.getElementByID("myTextBox");
  var l = document.getElementByID("myLabel");
  if (t.Length == 0) 
       {
         l.style.backgroundColor='red';
       }
 }

答案 2 :(得分:0)

有多个选项,一些服务器端和一些客户端,但在这两种情况下都涉及验证。基本上,您希望更改标签上的css类或其他样式属性。

答案 3 :(得分:0)

C#代码背后:

if(yourConditionText != "YourExpectedValue")
{
    youTextBox.BackColor = System.Drawing.Color.Red; 
}

答案 4 :(得分:0)

在服务器端按钮单击事件(当您双击aspx页面的“设计”视图中的按钮时将自动生成):

 protected void Button_Click(...)
    {
        if(txtYourTextBox.Text != "YourDesiredValue")
        {
            lblYourLabel.ForeColor = Color.Red;
        }
    }

更好的是,您可以使用String.Compare(推荐),如下所示:

if(string.Compare(txtYourTextBox.Text, "YourDesiredValue") != 0) //0 = Match
{
    lblYourLabel.ForeColor = Color.Red; //For backColor set BackColor property
}

希望它有所帮助!