更改以编程方式创建的按钮的属性

时间:2015-01-14 11:14:08

标签: c# button methods

我通过以下方式在我的应用程序中创建按钮:

List<Button> btnslist = new List<Button>();

for (int i = 0; i < nbrofbtns; i++)
{
   Button newButton = new Button();
   btnslist.Add(newButton);
   this.Controls.Add(newButton);

   newButton.Width = btnsidelength;       
   newButton.Height = btnsidelength;
   newButton.Top = btnsidelength 
                   * Convert.ToInt32(Math.Floor(Convert.ToDouble(i / Form2.puzzlesize)));
   newButton.Left = btnsidelength 
                    * Convert.ToInt32(
                            Math.Floor(Convert.ToDouble(i)) 
                            - Math.Floor((Convert.ToDouble(i)) 
                            / (Form2.puzzlesize)) * (Form2.puzzlesize));

   newButton.BackgroundImage = Lights_out_.Properties.Resources.LightsOutBlack;
   newButton.Tag = (i+1).ToString();

   newButton.Click += new EventHandler(Any_Button_Click);

然后我有一个单击任何按钮的方法。

void Any_Button_Click(object sender, EventArgs e)
{
    //the variable b has all the insformation that the single button had itself.
    Button b = (Button)sender;
    if (b.BackgroundImage == Lights_out_.Properties.Resources.LightsOutBlack)
    {
        MessageBox.Show(b.Tag.ToString());
        MessageBox.Show(btnslist[Convert.ToInt32(b.Tag)].BackgroundImage.ToString());
        btnslist[Convert.ToInt32(b.Tag)].BackgroundImage = 
                Lights_out_.Properties.Resources.LightsOutWhite;
        MessageBox.Show(btnslist[Convert.ToInt32(b.Tag)].BackgroundImage.ToString());
    }
    else
    {
        MessageBox.Show("b.backgroundimage != lightsoutblack. Backgroundimage = " 
                        + b.BackgroundImage.ToString());
    }
}

如何更改实际按钮中的数据(然后单击所述按钮)?我特意要改变backgroundimage。我怎么能这样做? (我还需要更改代码创建的其他按钮的backgroundimage。)

2 个答案:

答案 0 :(得分:0)

您正在处理已创建的每个按钮的Click事件 - 而sender中的Any_Button_Click实际上是点击了按钮

所以只需将b.BackgroundImage更改为您需要的任何内容。

答案 1 :(得分:0)

发件人对象 按钮:

Button b = (Button)sender;

...所以你应该可以直接更改它的属性:

b.WhateverPropsToChange = yourSetting;

PS:我认为这不是必要的,但如果按钮没有直接更新,您可能会尝试使用b.Refresh()让它知道某些内容已发生变化。