private void opc(object sender, EventArgs e)
{
//NOTE: buttons 13-16 share same click event
// needs for each loop
button13.Enabled = false;
button14.Enabled = false;
button15.Enabled = false;
button16.Enabled = false;
}
答案 0 :(得分:1)
你可以试试这个。
private void opc(object sender, EventArgs e)
{
for (int i = 13; i <= 16; i++)
{
Control[] buttons = this.Controls.Find(String.Format("button{0}", i), false);
if (buttons.Length > 0)
{
Button btn = (buttons[0] as Button);
btn.Click += btn_Click;
btn.Enabled = true; // or false
}
}
}
void btn_Click(object sender, EventArgs e)
{
MessageBox.Show((sender as Button).Name);
}
答案 1 :(得分:0)
见下面的代码:
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.button13.Click += new System.EventHandler(this.button_Click);
this.button14.Click += new System.EventHandler(this.button_Click);
this.button15.Click += new System.EventHandler(this.button_Click);
this.button16.Click += new System.EventHandler(this.button_Click);
}
private void button_Click(object sender, EventArgs e)
{
Button button = sender as Button;
string name = button.Text;
}
}
}
答案 2 :(得分:0)
您想将assignmens放入循环中吗?使用静态定义的按钮名称是不可能的AFAIK。您应该首先将按钮放入数组或集合中:
Button[] button = new Button[numberOfButtons];
for (int i=0; i<numberOfButtons; i++)
{
button[i] = new Button();
button[i].Click += new System.EventHandler(WhateverYouLike);
// ... some other property assignments, probably also rule-based
}
// ... and at a later time:
for (int i=0; i<numberOfButtons; i++) button[i].Enabled = false;