What is the best way to modify the CSS class of a particular textbox within a gridview using C# in ASP.NET?

I need assistance with removing and adding a CssClass to a specific textbox within a gridview. I have attempted the following code but it does not update the css for the textbox.

Here is the CSS in my .aspx page:

<style type="text/css">
   .erroramount
   {
       border:3px solid red
   }
</style>

In my button click event, here is my code for looping through the gridview. Depending on a condition, I want to change the border color of the textbox:

 var result = (from f in dtCloned.AsEnumerable()
                      group f by f.Field<string>("AssetDescription") into g
                      select
                      new
                      {
                          AssetDescription = g.Key,
                          TotalAmount = g.Sum(r => r.Field<double?>("Amount"))
                      });

foreach (var aAsset in result.AsEnumerable())
{
  if (aAsset.TotalAmount < 0)
  {
     foreach (GridViewRow arow in GridProjectDetails.Rows)
     {
         string AssetDescription = ((TextBox)arow.FindControl("TextAssetDescription")).Text;
         if (AssetDescription == aAsset.AssetDescription)
         {
             ((TextBox)arow.FindControl("TextAmount")).CssClass = "erroramount";
         }
     }
   }
 }

Answer №1

Your solution should function properly unless the code is inaccessible or unable to locate the control. An exception would have been thrown if the control was not found. Another method to set the class is by using the following syntax:

((TextBox)arow.FindControl("TextAmount")).Attributes["class"] = "erroramount";

Answer №2

Hey there! I managed to achieve the desired output by replacing the default CSS class and applying a new one to the textbox, which worked like a charm.

Below is the full code snippet:

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        ValidateAmount();
    }

    private void ValidateAmount()
    {
        System.Data.DataTable dtGridData = new DataTable();
        DataTable dtCloned = new DataTable();

        // Rest of the code remains the same as provided above...
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble making jQuery code disable input field based on checkbox status

Is there a way to automatically disable the price input field once the checkbox is checked and clear any existing text? I seem to be having trouble with my current code.. <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <scr ...

Explore various SVG paths by hovering to reveal or conceal different divs

Hi there, I'll do my best to explain clearly. If this question has already been asked, I apologize as I couldn't find an answer when searching. I've used SVG to create a map on my HTML webpage and it's looking great. I also have hidden ...

Received an error message indicating that the validation of the viewstate MAC failed while attempting to send a post request from Google App Engine using

For a project, I am tasked with fetching HTML from a website, but before I can access the page, I need to log in. To achieve this, I am using a low-level API URL fetch service. Here is a snippet of my code test: private String postPage(String loginPageHtm ...

The CSS styling for an active link is not functioning correctly on a single page when using sections

I recently received a zip file containing a template purchased from themeforest, with a request to make modifications. The template includes a horizontal navigation bar with links to various sections on the page. In the original template, when you click on ...

JavaScript Summation Calculation

I am currently working on calculating the sum of three scores and displaying the total as "Total:". However, I am facing an issue in dynamically updating the total whenever a score value changes. Is there a way to utilize the "onchange" event to achieve th ...

AngularJS not passing date data to web API

Greetings! I am currently working on a web application using AngularJS. I have a date value in AngularJS, for example 13-10-2017. In C#, I have the following field: public DateTime LicenseExpiryDate { get; set; } When I send 13-10-2017 in an AJAX reques ...

Interacting with Apexcharts: Exploring a Tiny Column with Hover

While using apexcharts, I encountered an issue with small columns. It can be quite challenging to render the tooltip properly because you have to hover very precisely over the column. Query: Is there a way to expand the hover area to make it easier to int ...

Conceal an entire div using CSS, especially if a portion of it remains unoccupied

Is there a way to conceal an entire division if a part of it is void? For instance, if "dd" is empty as indicated below, can I hide the entire class "test" so that the keyword Restrictions does not display either? I attempted .test dd:empty { display: none ...

Step-by-step guide on clipping a path from an image and adjusting the brightness of the remaining unclipped area

Struggling to use clip-path to create a QR code scanner effect on an image. I've tried multiple approaches but can't seem to get it right. Here's what I'm aiming for: https://i.stack.imgur.com/UFcLQ.png I want to clip a square shape f ...

Tips for achieving consistent outcomes on both IE and Chrome when utilizing the `min` attribute in HTML input tags

The display of input fields is inconsistent between IE (version 11) and Chrome (version 46.0.2490.71) when using the min option in the HTML input tag. In Chrome, the input fields appear extra long, while in IE they display correctly (same as when min is no ...

Store data in LocalStorage according to the selected value in the dropdown menu

Can you help me understand how to update the value of a localstorage item based on the selection made in a dropdown menu? <select id="theme" onchange=""> <option value="simple">Simple</option> <option valu ...

Unable to convert data from a string type to a custom object or model

My attempt to deserialize JSON data from an HTTP response into a specific Model is failing with the following exception: Message=Error converting value "{"Id":"1","UserName":"RK"}" to type 'ConsoleApp5 ...

Invoke JavaScript when the close button 'X' on the JQuery popup is clicked

I am implementing a Jquery pop up in my code: <script type="text/javascript"> function showAccessDialog() { var modal_dialog = $("#modal_dialog"); modal_dialog.dialog ( { title: "Access Lev ...

How to style the first dropdown value in AngularJS to appear bold?

Is there a way to style only the first value in a dropdown list as bold without using jQuery? Here is the code for the dropdown: <div class="col-xs-3"> <select-box id="ad-version-select" options="curItem.stats.version" model="state.version" i ...

Creating a button with a water-inspired design using CSS that works seamlessly across

Looking to create a stylish aqua-themed button that works seamlessly across different browsers. I'm new to CSS, so any guidance is appreciated. I found an online example that looks great in Chrome but fails to display properly in IE... Check out the ...

Unfortunately, Node Sass does not have compatibility with your current environment, which is Windows 64-bit with an unsupported runtime

Having been a regular user of Node.js to utilize gulp and sass for my HTML projects, I recently encountered a new issue. An error message stating "Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (57)" has no ...

Is It Possible to Align Text Horizontally within a Box?

Hey everyone! I'm trying to figure out how to display two elements, "1" and "new referral," side by side without the new referral having a green background. Any help would be greatly appreciated. I've shared my HTML and CSS code snippets below. I ...

The navigation bar is not extending to fill the entire width of the screen

I recently created a navigation bar using the nav tag and applied CSS to set the width, border, and padding. However, I noticed that there are some empty pixels on each side of the navigation bar that I can't seem to fill up. Here is the HTML code for ...

Html elements remain stationary and do not shift positions

I am attempting to customize a web page by repositioning an input text element. Below is the code I'm using: <body> <h1>Shopping List</h1> <input id="search" type="search"> <input id='newItem' type="t ...

Retrieving inline CSS value using jQuery

How do I retrieve the inline-css value of the second child within div #one using jQuery. <li id="one"> <h2>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Mollitia, velit!</h2> <div style="width: 1425px; height: 1080px ...