如果我有100个按钮,我想设置text =" Save"而id是一个自动编号,如saveButton_1,saveButton_2最好的方法是什么?没有动态生成的按钮可以通过后面的代码访问。
目前我这样做但似乎很长。
saveButton_1.value = saveButton_2.value ... till 100 = "Save"
答案 0 :(得分:0)
foreach (Button btn in this.Controls.OfType<Button>())
{
btn.Text = "Save";
}
答案 1 :(得分:0)
扩展@Adil的答案,如果你在容器中有按钮,你可以使用HtmlButton类型获取它们
IEnumerable< HtmlButton> btns = buttonContainer.Controls.OfType<HtmlButton>();
if(btns != null)
{
//get only the ones that have a special class to know which ones you need to update
var btnList = btns.Where(x => x.Attributes["class"] == "save-button");
//update the text for all that passed the filter
foreach(HtmlButton ctrl in btnList)
{
ctrl.InnerText = "Save Me";
}
}
HTML
<div id="buttonContainer" runat="server">
<button id="save1" type="button" class="save-button" runat="server">save 1</button>
<button id="save2" type="button" class="save-button" runat="server">save 1</button>
<button id="save3" type="button" class="save-button" runat="server">save 1</button>
<button id="save4" type="button" class="save-button" runat="server">save 1</button>
<button id="save5" type="button" runat="server">not save</button>
<button id="save6" type="button" class="save-button" runat="server">save 1</button>
<button id="save7" type="button" class="save-button" runat="server">save 1</button>
<button id="save8" type="button" class="save-button" runat="server">save 1</button>
<button id="save9" type="button" class="save-button" runat="server">save 1</button>
</div>
如果您没有同一个容器上的按钮,那么您将需要遍历您拥有的控件以获得正确的html按钮