c#user输入2维数组

时间:2016-05-06 21:26:49

标签: c# multidimensional-array

    private void button_add_Click(object sender, EventArgs e)
    {
        int data = Convert.ToInt32(data_textBox.Text);

        if (radioButton_2.Checked == true)
        {
            for (i = 0; i < Array2d.GetLength(0); i++)
            {
                for (j = 0; j < Array2d.GetLength(1); j++)
                {
                    Array2d[i,j] = data;
                }
            }
        }
        data_textBox.Clear();
    }

我想填充数组,每次输入的值都不是相同的值,但代码只是最后输入的值填充所有数组元素。

当我点击添加按钮时,它只是在数组中输入最后一个值。我该如何解决?

ui

1 个答案:

答案 0 :(得分:1)

最好的方法是让用户在多行文本框中输入所有值,用空格和返回值分隔。程序解析文本以创建数组。

以下是一些示例代码,可帮助您入门:

public partial class Form1 : Form
{
    int[,] array2d;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.array2d=ParseArray(textBox1.Lines, 4, 4);
    }
    public static int[,] ParseArray(string[] lines, int rows, int columns)
    {
        // allocate empty array
        var array=new int[rows, columns];
        // for each row of text
        for (int row=0; row<rows; row++)
        {
            // split into values separated by spaces, tabs, commas, or semicolons
            var items=lines[row].Split(',', ' ', ';', '\t');
            // for each value in the row
            for (int col=0; col<columns; col++)
            {
                // parse the string into an integer _safely_
                int x=0;
                int.TryParse(items[col], out x);
                array[row, col]=x;
            }
        }
        return array;
    }
    public static int[,] ParseArray(string text, int rows, int columns)
    {
        // split text into lines
        var lines=text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
        return ParseArray(lines, rows, columns);
    }
}