日期:2014-05-18  浏览次数:20818 次

动态按钮的颜色问题
button1,button2都是动态生成的.窗体里有一个我事先设好的button3.我想通过点击button3来实现对button1,button2的颜色改变.比如,我选择button1,点击button3后button1的颜色就变为红色了.

------解决方案--------------------
测试的整个代码就这样,改变颜色没问题的,你自己在button6的Click方法btnobj.BackColor = Color.Yellow这一句之前先重置其他按钮的颜色,这样就能起到点哪个变哪个,剩下按钮自动变回原来的颜色的效果了。
C# code

    public partial class Form1 : Form
    {
        private Button btnobj;
        List<Button> btnList = new List<Button>();
        private int count = 1;

        public Form1()
        {
            InitializeComponent();
        }

        private void DymaControlMouseDown(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            btn.BackColor = Color.Red;
            btnobj = btn;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            count = ++count;
            int i = btnList.Count;
            i++;
            Button btn = new Button();
            btn.BackColor = Color.Blue;
            btn.Text = "";
            btn.Size = new Size(50, 60);
            this.toolTip1.SetToolTip(btn, "位置" + (i + 3));
            btn.Click += new EventHandler(DymaControlMouseDown);
            btnList.Add(btn);

            if (i % 3 == 1)
            {
                btnList[i - 1].Location = new Point(21, 25 + ((i + 2) / 3 * 75));
            }
            else
                if (i % 3 == 2)
                {
                    btnList[i - 1].Location = new Point(130, 25 + ((i + 1) / 3 * 75));
                }
                else
                {
                    if (i % 3 == 0)

                        btnList[i - 1].Location = new Point(240, 25 + i / 3 * 75);
                }

            this.panel1.Controls.Add(btn);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            btnobj.BackColor = Color.Yellow;
        }
    }