I created a div tag like this:
System.Web.UI.HtmlControls.HtmlGenericControl dynDiv =
new System.Web.UI.HtmlControls.HtmlGenericControl(\"DIV\");
How about an extension method?
Here I have a show or hide method. Using my CSS class hidden.
public static class HtmlControlExtensions
{
public static void Hide(this HtmlControl ctrl)
{
if (!string.IsNullOrEmpty(ctrl.Attributes["class"]))
{
if (!ctrl.Attributes["class"].Contains("hidden"))
ctrl.Attributes.Add("class", ctrl.Attributes["class"] + " hidden");
}
else
{
ctrl.Attributes.Add("class", "hidden");
}
}
public static void Show(this HtmlControl ctrl)
{
if (!string.IsNullOrEmpty(ctrl.Attributes["class"]))
if (ctrl.Attributes["class"].Contains("hidden"))
ctrl.Attributes.Add("class", ctrl.Attributes["class"].Replace("hidden", ""));
}
}
Then when you want to show or hide your control:
myUserControl.Hide();
//... some other code
myUserControl.Show();
If you're going to be repeating this, might as well have an extension method:
// appends a string class to the html controls class attribute
public static void AddClass(this HtmlControl control, string newClass)
{
if (control.Attributes["class"].IsNotNullAndNotEmpty())
{
control.Attributes["class"] += " " + newClass;
}
else
{
control.Attributes["class"] = newClass;
}
}
You don't add the css file to the div, you add a class to it then put your import at the top of the HTML page like so:
<link href="../files/external.css" rel="stylesheet" type="text/css" />
Then add a class like the following to your code: 'myStyle'.
Then in the css file do something like:
.myStyle
{
border-style: 1px solid #DBE0E4;
}
To add a class to a div that is generated via the HtmlGenericControl
way you can use:
div1.Attributes.Add("class", "classname");
If you are using the Panel
option, it would be:
panel1.CssClass = "classname";
I think the answer of Curt is correct, however, what if you want to add a class to a div that already has a class declared in the ASP.NET code.
Here is my solution for that, it is a generic method so you can call it directly as this:
Asp Net Div declaration:
<div id="divButtonWrapper" runat="server" class="text-center smallbutton fixPad">
Code to add class:
divButtonWrapper.AddClassToHtmlControl("nameOfYourCssClass")
Generic class:
public static class HtmlGenericControlExtensions
{
public static void AddClassToHtmlControl(this HtmlGenericControl htmlGenericControl, string className)
{
if (string.IsNullOrWhiteSpace(className))
return;
htmlGenericControl
.Attributes.Add("class", string.Join(" ", htmlGenericControl
.Attributes["class"]
.Split(' ')
.Except(new[] { "", className })
.Concat(new[] { className })
.ToArray()));
}
}
dynDiv.Attributes["class"] = "myCssClass";