I have the following on my interface / webform:
Now I have a condition in my
I find it better to use REGEX replace since replacing class could exist as partial name in other classes which would break them. So I'm using the following extension method:
public static void RemoveClass(this WebControl control, string classToRemove)
{
if (control == null)
return;
control.CssClass = Regex.Replace(control.CssClass, @"(^|\s)" + classToRemove + @"($|\s)", " ");
}
If a control has several classes you can remove one of those classes by editing the class string. Both of these methods require assigning an ID to the HTML element so that you can target it in the code behind.
<asp:Panel ID="mydiv" CssClass="forceHeight class2 class3" runat="server" />
VB.NET
mydiv.CssClass = mydiv.CssClass.Replace("forceHeight", "").Trim()
C#
mydiv.CssClass = mydiv.CssClass.Replace("forceHeight", "").Trim();
OR using html generic control
<div id="mydiv" class="forceHeight class2 class3" runat="server" />
VB.NET
mydiv.Attributes("class") = mydiv.Attributes("class").Replace("forceHeight", "").Trim()
C#
mydiv.Attributes["class"] = mydiv.Attributes["class"].Replace("forceHeight", "").Trim();
Optional Trim
to remove trailing white space.
VB.NET
mydiv.Attributes("class") = ""
C#
mydiv.Attributes["class"] = "";
Me.mydiv.Attributes.Remove("class")
is much better since it won't leave a stub behind. It'll produce a cleaner HTML tag.
<div id="mydiv"></div>
If you use this,
Me.mydiv.Attributes("class") = ""
it will produce this instead
<div id="mydiv" class=""></div>
OR <div id="mydiv" class></div>
mydiv.Attributes["class"] = mydiv.Attributes["class"].ToString().Replace("ClassName","")
public static void appendCssClass(HtmlGenericControl htmlGenericControl, string cssClassName)
{
htmlGenericControl.Attributes.Add("class",
htmlGenericControl.Attributes["class"].ToString() + " " + cssClassName);
}
public static void removeCssClass(HtmlGenericControl htmlGenericControl, string cssClassName)
{
htmlGenericControl.Attributes.Add("class",
htmlGenericControl.Attributes["class"].Replace(cssClassName, ""));
}
mydiv.Attributes("class") = mydiv.Attributes("class").Replace("forceHeight", "")
The other answers did not work for me. Like the OP said, I'm not getting myDiv.CssClass
in IntelliSense
.