日期:2014-05-18 浏览次数:20846 次
private void btnDm_Click(object sender, EventArgs e) { Button btnDm = sender as Button; if(btnDm==null) return; if (btnDm.ForeColor == Color.LightGray) { btnDm.ForeColor = Color.OrangeRed; } else { btnDm.ForeColor = Color.LightGray; } } btnDm001.Click+=new EventHandler(btnDm_Click); btnDm002.Click+=new EventHandler(btnDm_Click); btnDm003.Click+=new EventHandler(btnDm_Click); ...
------解决方案--------------------
不用呀,你继承个button,重写下按下事件,在这里换图片或颜色。
然后所有地方都用这个button。
这就是所谓的自定义控件的用法。
------解决方案--------------------
//事件方法可以简化下 private void btnDm001_Click(object sender, EventArgs e) { var btn = (Button)sender; btn.ForeColor = btn.ForeColor != Color.LightGray ? Color.LightGray : Color.OrangeRed; } // 用这段代码给 btnDm001 - btnDm100 的按钮绑定事件 for (int i = 1; i <= 100; i++) { this.Controls.Find("btnDm" + i.ToString("D3"), false)[0].Click += new EventHandler(btnDm001_Click); }
------解决方案--------------------
只要写一个函数,每个按钮都绑定这个函数。
如果你的按钮命名是有规律的,或者是统一放在一个容器里。可以用循环绑定。
foreach (Control c in this.Controls)
{
if (c is Button)
(c as Button).Click+=new EventHandler(btnDm_Click);
}
------解决方案--------------------
假设你的100个按钮的Name为buttonDm001-buttonDm100,这样写:
private void Form1_Load(object sender, EventArgs e) { for (int i = 1; i <= 100; i++) this.Controls["buttonDm" + i.ToString("D3")].Click += new EventHandler(Form1_Click); } void Form1_Click(object sender, EventArgs e) { Button btn = sender as Button; if (btn.ForeColor == Color.LightGray) btn.ForeColor = Color.OrangeRed; else btn.ForeColor = Color.LightGray; }