以编程方式更改文本框的 Css 类

Change CssClass of an Textbox programatically

我的第一个 ASP 项目有点问题。 我提供用户和输入掩码来输入数据。在某些时候,我想控制输入是否为数字。如果不是,我想更改文本框的边框颜色。 这是我的文本框:

<asp:TextBox ID="tbOnlyNumeric" runat="server" Height="30px" CssClass="MyNumericBox" autocomplete="off"></asp:TextBox>

盒子的样式是这样的:

.MyNumericBox
{
    width:250px;
    overflow: auto;
    font-size: 20px;
    position:relative;
    right:111px;
    border-color: #dcdcdc;
    padding: 4px;
    margin:15px;
    border-width: 2px;
    border-radius: 10px;
    border-style: solid;
    transition: box-shadow 0.3s, border 0.3s;
    text-align: right;
    padding-right: 18px;
    outline: none;
}

我的想法是将文本框的文本转换为 try-catch-statement:

     try
     {
        if (string.IsNullOrWhiteSpace(tbOnlyNumeric.Text))
        {
          throw new Exception();
        }
        else
        {
          salesExpected = Convert.ToInt32(tbOnlyNumeric.Text.ToString().Replace(".", string.Empty));
        }
     }
     catch (Exception ex)
     {
          debugLabel.Text = "EX";
          correct = false;
          tbOnlyNumeric.CssClass = tbSalesExpected.CssClass.Replace("MyExpectedBox", "MyExpectedBoxWrong");
     }

因此,如果我的文本框有问题,它应该如下所示:

但它看起来像这样:

我已经注意到,如果在 chrome 中观看,旧的 css class 会被删除,但新的不会添加。

知道为什么吗?

提前致谢

你能试试这个代码吗?把这个放在你的 catch 语句中

ScriptManager.RegisterClientStartUpScript(this,this.GetType(),"pop","changeCssStyle();",true);

//在你的 aspx 文件的头部创建一个脚本来改变 //css 文本框的样式

<script type="text/javascript">
   function changeCssStyle(){
   //if you are using a master page refer the id of textbox to the id of 
   //head content in master page e.g. MainContent_tbOnlyNumeric

   //lets assume you already have reference to jquery in your head section
   $('#MainContent_tbOnlyNumeric').css("border-color","red");

   } 
</script>

终于想通了,使用:

tbSalesExpected.CssClass = "MyExpectedBoxWrong";

而不是:

tbOnlyNumeric.CssClass = tbSalesExpected.CssClass.Replace("MyExpectedBox", "MyExpectedBoxWrong");

解决了问题。

感谢您的回答和评论!