在c#

时间:2016-01-09 20:08:20

标签: c# sorting button

用户以编程方式添加了大量按钮。 按钮由x和y数字创建(用户输入它们)。 每个x都有一个y按钮。 所以,如果我的x数是2,y数是3,那么我将在表单上命名和插入按钮,如:

image1

现在,我如何使用两个FOR语句在表单上定位按钮,如:

enter image description here

到目前为止,这是我的代码:

int left = 50;
int top = 50;
int all_zd=x*y;
Button[] btn_arr = new Button[all_zd];
for (int i = 1; i <=y; i++ ) 
{
    for (int j = 1; j <= x; j++)
    {
        //Button btn = new Button();
        btn_arr[j] = new Button();
        {
            btn_arr[j].Name = j.ToString() + "t" + i.ToString();
            btn_arr[j].Text = j.ToString() + "ff" + i.ToString();
            btn_arr[j].Height = 20;
            btn_arr[j].Width = 50;
            btn_arr[j].Location = new Point(left,top);
            top += btn_arr[j].Height + 2; 
            this.Controls.Add(btn_arr[j]);
        }
    }
}

也许if语句?

if ((i == 1 && j % x == 1) top+= btn_arr[j].Height + 2;

2 个答案:

答案 0 :(得分:0)

尝试以下

  var left = 0;
  var top = 0;
  var btnWith = 20;
  var btnHeigh = 50;


  int x = 2, y = 3;
  for (var i = 0; i < x; i++)
  {
    for (var j = 0; j < y; j++)
    {
      var btn = new Button();
      btn.Name = j + "t" + i;
      btn.Text = j + "ff" + i;
      btn.Height = btnHeigh ;
      btn.Width = btnWith;
      btn.Location = new Point(left, top);

      left += btnWith;
      Controls.Add(btn);
    }
    top += btnHeigh;
  }

答案 1 :(得分:0)

我做了两种方法,创建垂直按钮和水平按钮。

    private void CreateVerticalButtons()
    {
        const int LEFT = 200;
        var top = 50;
        var x = int.Parse(X.Text);
        var y = int.Parse(Y.Text);

        for (var i = 1; i <= y; i++)
        {
            for (var j = 1; j <= x; j++)
            {
                var btn = new Button();
                btn.Text = string.Format("{0}ff{1}", j, i);
                btn.Height = 20; btn.Width = 50;
                btn.Top = top;
                btn.Left = LEFT;
                top += 22;
                this.Controls.Add(btn);
            }
        }
    }

    private void CreateHorizontalButtons()
    {
        const int TOP = 100;
        var left = 200;

        var x = int.Parse(X.Text);
        var y = int.Parse(Y.Text);

        for (var i = 1; i <= y; i++)
        {
            var top = TOP;
            for (var j = 1; j <= x; j++)
            {
                var btn = new Button();
                btn.Text = string.Format("{0}ff{1}", j, i);
                btn.Height = 20; btn.Width = 50;
                btn.Top = top;
                btn.Left = left;
                top -= 22;
                this.Controls.Add(btn);
            }

            left += 52;
        }
    }