how to add css class to html generic control div?

前端 未结 9 2207
名媛妹妹
名媛妹妹 2020-12-13 08:21

I created a div tag like this:

System.Web.UI.HtmlControls.HtmlGenericControl dynDiv = 
    new System.Web.UI.HtmlControls.HtmlGenericControl(\"DIV\");
         


        
9条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 08:38

    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();
    

提交回复
热议问题