title: How do I cast an HtmlGenericControl as a WebControl?
body: <p>... I am trying to dynamically add or remove classes to my ASP controls using this code (which I found via my great pair-programming friend who shall be known as 'Mr G')</p>
  
  <pre><code>public static class WebHelper
  {
      public static void AddCssClass(this WebControl control, string cssClass) {
          List&lt;string&gt; classes;
          if (!string.IsNullOrWhiteSpace(control.CssClass)) 
          {
              classes = control.CssClass.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
              if (!classes.Contains(cssClass))
                  classes.Add(cssClass);
          }
          else
          {
              classes = new List&lt;string&gt; { cssClass };
          }
          control.CssClass = string.Join(" ", classes.ToArray());
      }
  
      public static void RemoveCssClass(this WebControl control, string cssClass)
      {
          List&lt;string&gt; classes = new List&lt;string&gt;();
          if (!string.IsNullOrWhiteSpace(control.CssClass))
          {
              classes = control.CssClass.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
          }
          classes.Remove(cssClass);
          control.CssClass = string.Join(" ", classes.ToArray());
      }
  }
  </code></pre>
  
  <p>Unfortunately I can't find a way to pass my HtmlGenericControls to them... I've tried the obvious:</p>
  
  <pre><code>WebControl test1 = (WebControl)Page.FindControl("divcontent");
  WebHelper.AddCssClass(test1, centredClass);
  </code></pre>
  
  <p>But I get:
  System.InvalidCastException: Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlGenericControl' to type 'System.Web.UI.WebControls.WebControl'.</p>
  
  <p>I'm still relatively inexperienced at C#, Visual Studio etc as my background is Ye Olde Pick BASIC, so please explain simply how I either cast my control, or amend the code so it will achieve the end goal of being able to add or remove classes without losing any existing ones.</p>
  
  <p>Many thanks! Ross</p>