Change text for multiple buttons in one operation

纵然是瞬间 提交于 2020-01-04 06:07:14

问题


I have a form which consist of many buttons (50+) and they all have the same name except for the suffix number. (btn_0, btn_1, btn_3, etc.)

I want to change the text of those buttons in one operation.

Is there a way of treating buttons like arrays?

btn_[i].Text = "something"? 

Maybe execute a string?

"btn_{0}.Text=\"something\""

回答1:


you will need to access each button at a time to do this.

Do it in a loop like this

foreach(var btn in this.Controls)
{
    Button tmpbtn;
    try
    {
        tmpbtn = (Button) btn;
    }
    catch(InvalidCastException e)
    {
        //perform required exception handelling if any.
    }
    if(tmpbtn != null)
    {
       if(string.Compare(tmpbtn.Name,0,"btn_",0,4) == 0)
       {
            tmpbtn.Text = "Somthing"; //Place your text here
       }
    }
}

Have a look for the Overloaded Compare method used.




回答2:


if you know how many buttons there is you can make a loop. though it's not perfect and there might be a smarter way to do this but I can't see why I wouldn't work




回答3:


Don't know specifics but the pattern probably goes like this

for each(Control c in this.controls)
{
   if(c is Button) //Check the type
   {
       Button b = c as button;
       b.Text="new text";
    }
}

or use excel with its autofil and text concatenation abilities to do it as a block of text. eg

btn1.text="hi";
btn2.text="world";
...



回答4:


why not use jquery to rename all at once?

jQuery("form :button").attr('value','Saved!')


来源:https://stackoverflow.com/questions/4724347/change-text-for-multiple-buttons-in-one-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!