为什么我的面板显示我的c#应用程序中的所有按钮?

时间:2010-06-04 18:07:26

标签: c# panel dynamic

我的Windows窗体应用程序中的面板不包括我要求的所有按钮。它只显示1个按钮,这是代码

 private void AddAlphaButtons()
        {
            char alphaStart = Char.Parse("A");
            char alphaEnd = Char.Parse("Z");

        for (char i = alphaStart; i <= alphaEnd; i++)
        {
            string anchorLetter = i.ToString();
            Button Buttonx = new Button();
            Buttonx.Name = "button " + anchorLetter;
            Buttonx.Text = anchorLetter;
            Buttonx.BackColor = Color.DarkSlateBlue;
            Buttonx.ForeColor = Color.GreenYellow;
            Buttonx.Width = 30;
            Buttonx.Height = 30;

            this.panelButtons.Controls.Add(Buttonx);

            //Buttonx.Click += new System.EventHandler(this.MyButton_Click);
        }
    }

2 个答案:

答案 0 :(得分:6)

他们不是都会在同一个位置吗?

尝试设置Buttonx.Location = new Point(100, 200);

(但不同的按钮有不同的点)

答案 1 :(得分:0)

您可以使用FlowLayoutPanel来处理布局,或者您需要自己跟踪位置,或者看起来像这样:

private void AddAlphaButtons()
{
    char alphaStart = Char.Parse("A");
    char alphaEnd = Char.Parse("Z");   

    int x = 0;  // used for location info
    int y = 0;  // used for location info

    for (char i = alphaStart; i <= alphaEnd; i++)
    {
        string anchorLetter = i.ToString();
        Button Buttonx = new Button();
        Buttonx.Name = "button " + anchorLetter;
        Buttonx.Text = anchorLetter;
        Buttonx.BackColor = Color.DarkSlateBlue;
        Buttonx.ForeColor = Color.GreenYellow;
        Buttonx.Width = 30;
        Buttonx.Height = 30;

        // set button location
        Buttonx.Location = new Point(x, y);

        x+=30;
        if(x > panel1.Width - 30)
        { 
            x = 30;
            y+=30;
        }

        this.panelButtons.Controls.Add(Buttonx);

        //Buttonx.Click += new System.EventHandler(this.MyButton_Click);
     }
}