2016-05-06 70 views
-2
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(); 
    } 

我想填充數組,我每次輸入的值不是相同的值,但代碼只是最後輸入的值填充所有數組元素。c#用戶輸入2維數組

當我點擊添加按鈕它只是最後輸入數組中的值。我如何解決它?

ui

+0

請提供樣品字符串。 –

+0

你想在這裏修復什麼?你知道這段代碼爲數組的每個元素設置了相同的值嗎?如果你沒有很好地解釋你的目標是什麼,那麼你的問題有可能被關閉,因爲不清楚你在問什麼問題 – Steve

+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); 
    } 
} 
+0

謝謝你的幫助。 –

+0

我沒有在代碼中檢查錯誤。如果用戶輸入的數字少於預期,則會失敗。另外爲了做數學,使用鋸齒形數組(而不是2d數組)更容易使用鋸齒形數組(「int [] []」類型)。 – ja72