我现在在做一个界面,界面中用到很多按钮,我想用代码来生成按钮,是否能实现呢?该如何实现呢?还有一个功能就是,我有按钮1,2,3,4,5,6......等N个,假设我按了第5个按钮,那么1到4的按钮的enabled=false;按了第N个,第一个到第N-1个的按钮的enabled=false;该怎么实现,纠结我大半天,求指教
Button[] _btnList; private void CreateButton(Control parent, int n) { _btnList = new Button[n]; for(int i =1; i <= n; i++) { Button btn = new Button(); btn.Text = i.ToString(); btn.Clicked += new EventHandler(btnClickedHandler); btn.Location = new Point(0, (i-1)*btn.height + 5); parent.Controls.Add(btn); btn.Name="btn" + i.ToString(); btn.Tag = i; _btnList[i - 1] = btn; } } private void btnClickedHandler(object sender, EventArgs e) { Button btn = sender as Button; for(int i = 1; i < (int)btn.Tag; i++) { _btnList[i-1].Enabled = false; } }
以上是一个方案,你可以举一反三。
for循环。
for(int i =0; i <DisplayNameNodes.Count; i++)
{
Button folderButton =newButton();
folderButton.Width=150;
folderButton.Height=70;
folderButton.ForeColor=Color.Black;
folderButton.Text=DisplayNameNodes[i].InnerText;
//This will work and add button to your Form.
this.Controls.Add(folderButton );
//you can't get Control.Add on a type, it's not a static method. It only works on instances.
//GUIWevbDav.Controls.Add
}
根据for循环创建控件
for (int i = 0; i < 100; i++)
{
Button newBtn = new Button();
//设置控件的height、width
newBtn.Size = new System.Drawing.Size(75,20);
newBtn.Name = "btn" + i.ToString();
this.Controls.Add(newBtn);
}
private void button2_Click_1(object sender, EventArgs e)
{
//根据你说的情况,我们可以在button的name名字上文章
//比如说第一个按钮的name叫btn1,第二个叫btn2,依此类推
//当我们点击按钮,触发事件时。
//先获取当前按钮的name
string btnName = ((Button)sender).Name;
try
{
int num = Convert.ToInt32(btnName.Last().ToString());
for (int i = 1; i < num; i++)
{
btnName = "btn" + i.ToString();
//按Name在当前窗体中找到button
Control [] btnCon= this.Controls.Find(btnName,true);
foreach (var item in btnCon)
{
item.Enabled = false;
}
}
}
catch (Exception)
{
throw;
}
}
根据楼上的也可以 你把button的tag指按顺序如1,2,3这样的赋值形式
找的时候直接根据控件的tag指,和我那差不多