将1维阵列处理为2天

时间:2017-03-30 07:35:45

标签: c# arrays forms

我正在为我的学校做作业,我有一个带有按钮的数组,从0到42一直显示,表格是这样的:(我用字母给你看,所以格式更容易明白,记住a = 0):

  

a b c d e f g

     

h i j k l m n

     

o p q r s t u

我想执行诸如获取x,y坐标值,设置x,y值的操作。我已经尝试了一些东西,但它们似乎都没有按照我希望的方式工作。而且我不知道此时是否值得将我的作业转换为2D。

 public partial class Form1 : Form
{
    Button[] Buttons = new Button[42];
    bool one1 = true;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.BackColor = Color.Red;
        this.Width = 500;
        this.Height = 500;

        for (int i = 0; i < Buttons.Length; i++)
        {
            int index = i;
            this.Buttons[i] = new Button();
            int x = 50 + (i % 7) * 50;
            int y = 50 + (i / 7) * 50;

            this.Buttons[i].Location = new System.Drawing.Point(x, y);
            this.Buttons[i].Name = "btn" + (index + 1);
            this.Buttons[i].Size = new System.Drawing.Size(50, 50);
            this.Buttons[i].TabIndex = i;
            this.Buttons[i].Text = Convert.ToString(index);
            this.Buttons[i].UseVisualStyleBackColor = true;
            this.Buttons[i].Visible = true;

            Buttons[i].Click += (sender1, ex) => this.buttonHasBeenPressed(sender1, index);
            this.Controls.Add(Buttons[i]);
        }
    }

编辑:我添加了生成数组的代码。我试过用这样的东西:

  var startValue = (Button)sender;
int xCenter = startValue.Location.X
int yCenter = startValue.Location.Y

但由于某种原因,它没有按照我的意愿行事。基本上我想生成代码,当用户单击按钮时,代码可以检查周围的按钮以获取信息。

1 个答案:

答案 0 :(得分:1)

如果您定义每行有多少条目,则可以计算一维数组内的偏移量

public static void Main() {

    const int elementsPerRow = 5;
    var data = new [] {"A", "B", "C", "D", "E", 
                       "F", "G", "H", "I", "J", 
                       "K", "L", "M", "N", "O", 
                       "P", "Q", "R", "S", "T"
                      };

    var aIndex = GetIndex(0, 0, elementsPerRow);
    var eIndex = GetIndex(0, 4, elementsPerRow);
    var pIndex = GetIndex(3, 0, elementsPerRow);
    var tIndex = GetIndex(3, 4, elementsPerRow);

    Console.WriteLine(data[aIndex]); // A
    Console.WriteLine(data[eIndex]); // E
    Console.WriteLine(data[pIndex]); // P
    Console.WriteLine(data[tIndex]); // T
}

public static int GetIndex(int rowIndex, int columnIndex, int elementsPerRow) {
    var index = rowIndex * elementsPerRow + columnIndex;
    return index;
}

.net Fiddle