如何从文本框数组获取值并将其推入二维数组?

问题描述 投票:1回答:1

我创建一个大小取决于用户的矩阵,我生成随机数。问题是如何从文本框数组中获取所有值并将它们写入另一个数组。还是有更合理的方法?但是事实是,我需要能够在行和列中“行走”。用于创建矩阵的表格

public void gen__matrix()
{
    int row = Convert.ToInt32(txt_row.Text);
    int col = Convert.ToInt32(txt_col.Text);
    int[,] ar_matrix = new int[row, col];

    addTextBox(row, col, ar_matrix);
}

带有值的TextBox矩阵本身

this

public void addTextBox(int row, int col, int[,] ar_matrix)
{
    Random rnd = new Random();

    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            double rnd_val = rnd.Next(1, col + 1);
            TextBox textboxEdit = new TextBox();

            int pos_x_lb = 10;
            int pos_x_lb_step = 85;

            int pos_y_lb = 10;
            int pos_y_lb_step = 30;

            textboxEdit.Size = new Size(80, 20);
            textboxEdit.Name = Convert.ToString(row + i);
            textboxEdit.Text = Convert.ToString(Math.Round(rnd_val, 3));
            textboxEdit.Font = new Font(textboxEdit.Font.FontFamily, 12);
            textboxEdit.TextAlign = HorizontalAlignment.Center;

            textboxEdit.Location = new Point(pos_x_lb + (j * pos_x_lb_step), pos_y_lb + (pos_y_lb_step * i));
            panel1.Controls.Add(textboxEdit);
        }
    }
}
c# arrays multidimensional-array textbox
1个回答
0
投票

一种方法是将事件处理程序附加到textChangedEvent。这将需要您事先知道要更新的矩阵。

textboxEdit.TextChanged += (o, e) =>
        {
            ar_matrix[i, j] = int.TryParse(textboxEdit.Text, out var num) ? num : ar_matrix[i, j];
        };

另一种选择是设置每个文本框的Tag属性

textboxEdit.Tag = (i, j);

并遍历所有设置了标签属性的文本框:

foreach (var textBox in panel.Controls.OfType<TextBox>())
        {
            if (textBox.Tag is ValueTuple<int, int> indices && 
                int.TryParse(textBox.Text, out var num))
            {
                ar_matrix[indices.Item1, indices.Item2] = num;
            }
        }

免责声明:所有代码均未经测试

© www.soinside.com 2019 - 2024. All rights reserved.