C# 谁能简化这段代码 ?

来源:百度知道 编辑:UC知道 时间:2024/05/23 00:06:30
button2.BackgroundImage = imageList1.Images[index[1]];
button3.BackgroundImage = imageList1.Images[index[2]];
button4.BackgroundImage = imageList1.Images[index[3]];
button5.BackgroundImage = imageList1.Images[index[4]];
button6.BackgroundImage = imageList1.Images[index[5]];
button7.BackgroundImage = imageList1.Images[index[6]];
button8.BackgroundImage = imageList1.Images[index[7]];
button9.BackgroundImage = imageList1.Images[index[8]];
button10.BackgroundImage = imageList1.Images[index[9]];
button11.BackgroundImage = imageList1.Images[index[10]];

用for循环能办的到吗?

一楼的大哥,试验过没,我试了一下都快给我整死机了

for (int i = 2; i <= 11; i++)
{
object[] o = (this.Controls.Find("button" + i, false));
if (o.Length>0)
{
Button btn = (Button)o[0];
btn.BackgroundImage = imageList1.Images[index[i-1]];

}
}
我没做过WINFORM的! 呵呵! 帮你去做了做! 可能很糟糕的!
不过效果能达到你要的了!
你可以试一下!

用for循环可以达到要求,你可以定义一个变量i,是从2到11的

Button[] btn={button1,
button2,button3,button4,button5,button6,button7,button8,button9,button10,button11};
for(int i=0;i<btn.Length;i++)
{
btn[i].BackgroundImage = imageList1.Images[index[i];
}
//你的没有button1,我擅作主张给加上了,呵呵,注意对应关系就行了

落月Prc的正确 一楼的是JS的方法 在这里不适用