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

标签 c# css asp.net textbox

我的第一个 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");
     }

所以如果我的文本框有问题,它应该是这样的:

enter image description here

但它看起来像这样:

enter image description here

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

知道为什么吗?

提前致谢

最佳答案

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

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

//在你的aspx文件的head部分创建一个脚本来改变 //文本框的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>

关于c# - 以编程方式更改文本框的 Css 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33630464/

相关文章:

html - 仅当汉堡菜单出现时,如何使用 Bootstrap 将品牌带到 Navbar 的中心?

c# - 动态创建动态 RadioButtonsList

c# - 如何使用 C# 在转发器控件中查找标签值?

c# - 使用 Azure Active Directory 对用户进行身份验证后执行代码

c# - 传输大文件 : combining streamed transfer and content-length

javascript - 使用 Jquery 更改 url 时向正文添加类?

c# - 我应该如何为应用程序实现 OAuth?

c# - 如何使用 ADO.NET 创建数据库触发器

c# - 如何最好地限制通用 <T> 类中的类型,其中所有类型都派生自同一基类

CssResource 改变样式