Felix Gerber
Felix Gerber

Reputation: 1651

Change CssClass of an Textbox programatically

I've got a little Problem with my first ASP-Project. Im offering the user and input-mask to enter data. At some points I want to control if the input is numeric. If not I want to change the border color of my Textbox. This is my Textbox:

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

The style of the box looks like that:

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

My idea was to cast the the Text of the textbox in an try-catch-statment:

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

So if there is something wrong with my textbox it should look like that:

enter image description here

but instead it looks like that:

enter image description here

I already noticed that if watch it in chrome the old css class is deleted but the new one isn't addet.

Any idea why?

Thanks in advance

Upvotes: 0

Views: 2727

Answers (2)

Felix Gerber
Felix Gerber

Reputation: 1651

Finally figured outthat using:

tbSalesExpected.CssClass = "MyExpectedBoxWrong";

instead of:

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

fixes the problem.

Thanks for your answers and comments!

Upvotes: 1

Francis Saul
Francis Saul

Reputation: 740

could you try this code. put this in your catch statement

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

//in the head section of your aspx file create a script that will change the //css style of the textbox

<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>

Upvotes: 1

Related Questions