c# html 动态添加控件 属性获得,.net c#动态创建HTML按钮控件并在其中嵌套i标签

I created a simple HTML Button within c# as

Button btn = new Button();

btn.ID="myID";

btn.Click+=new EventHandler(someFunc);

which works perfectly fine as expected. But all I need to do is to insert an icon within it.

Similar to something like this.

add

Could someone please guide as to how to insert this within the button?

Talk1:

Why are you adding i element within button? Instead use btn.style = "font-style:italic;" and btn.text = "add"; to add the text and italic style to the button, add the required class material-icons with the button itself

Solutions1

Instead of using Button you have to use HtmlButton and have server click event, because WebControls Button will render like

Also someFunc should be event not string

Following is the complete code that you can use

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

System.Web.UI.HtmlControls.HtmlButton btn = new System.Web.UI.HtmlControls.HtmlButton();

btn.ID = "myID";

btn.Attributes["class"] = "mdl-button mdl-js-button mdl-button--fab mdl-button--colored";

btn.ServerClick += new EventHandler(someFunc);

btn.InnerHtml = "add";

// you can add your button to some other parent control or to form

myCustomPanel.Controls.Add(btn);

}

}

protected void someFunc(object sender, EventArgs e)

{

// your code

}

Make sure to add your button in form or some other control inside form.

Solutions2

You can create a HtmlGenericControl object and add all the relevant properties like InnerText,class etc and finally add this object to the button's controls collection. This will give you the expected output:-

HtmlGenericControl iTag = new HtmlGenericControl("i");

iTag.InnerText = "Add";

iTag.Attributes["class"] = "material-icons";

btn.Controls.Add(iTag);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值