首页 新闻 会员 周边

C#winform窗体

0
悬赏园豆:30 [已解决问题] 解决于 2012-05-05 09:53

我现在在做一个界面,界面中用到很多按钮,我想用代码来生成按钮,是否能实现呢?该如何实现呢?还有一个功能就是,我有按钮1,2,3,4,5,6......等N个,假设我按了第5个按钮,那么1到4的按钮的enabled=false;按了第N个,第一个到第N-1个的按钮的enabled=false;该怎么实现,纠结我大半天,求指教

Mr丶Lee的主页 Mr丶Lee | 初学一级 | 园豆:10
提问于:2012-04-25 23:12
< >
分享
最佳答案
0
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;
    }
}

以上是一个方案,你可以举一反三。

收获园豆:10
无之无 | 大侠五级 |园豆:5095 | 2012-04-26 08:43
其他回答(2)
0

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

}
收获园豆:10
悟行 | 园豆:12559 (专家六级) | 2012-04-25 23:34
0

根据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;
}
}

收获园豆:10
┢┦偉 | 园豆:1240 (小虾三级) | 2012-04-26 09:23

根据楼上的也可以  你把button的tag指按顺序如1,2,3这样的赋值形式

 

找的时候直接根据控件的tag指,和我那差不多

支持(0) 反对(0) ┢┦偉 | 园豆:1240 (小虾三级) | 2012-04-26 10:27
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册