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

汤米·拉耶特(TommyRäjert)

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

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。我该怎么办?(我还需要更改代码创建的其他一些按钮的背景图像。)

贾尔坦

发送者对象按钮:

Button b = (Button)sender;

...因此您应该能够直接更改其属性:

b.WhateverPropsToChange = yourSetting;

PS:我认为这不是必需的,但是如果不直接更新按钮,则可以尝试使用b.Refresh()它来告知某些更改。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章