2012-03-07 71 views
1

我必須寫一個程序(C#,WPF),其中數據被從〜30個文本框檢索。我想通過循環文本框。我試圖創建文本框的數組,但由於每一個方法,我不得不多次重新初始化這個數組它沒有很好地工作。如何將多個文本框的內容讀取到數組中?

TextBox[] subjects = { textBox1, textBox2, textBox3, textBox4, textBox5, textBox6, textBox7, textBox8, textBox9, textBox10 }; 
TextBox[] credits = { textBox11, textBox12, textBox13, textBox14, textBox15, textBox16, textBox17, textBox18, textBox19, textBox20 }; 
TextBox[] marks = { textBox21, textBox22, textBox23, textBox24, textBox25, textBox26, textBox27, textBox28, textBox29, textBox30 }; 

Subject.SubjectName = subjects[selection].Text; 
Subject.AmountOfCredits= Convert.ToInt32(credits[selection].Text); 
Subject.Mark = Convert.ToInt32(marks[selection].Text); 

主要的問題是,如果有任何其他的方式來循環使用所有這些控件,而無需創建文本框的陣列?

在此先感謝。

回答

0

你有沒有考慮使用DataGrid控件?您可以有三列(主題,積分和標記),並通過SelectedItem屬性輕鬆獲取所選記錄?

另一種選擇是使用一個ItemsControl。你可以樣式ItemTemplate中有三個文本框,您數據綁定直接主題的屬性。 ItemsControl的ItemsSource將被綁定到一個可觀察的主體集合。有關如何執行此操作的更多信息,請訪問Data Templating Overview上的Microsoft幫助。

1

可以在每次文本框的屬性綁定。然後在每個屬性的setter中,您可以在數組中設置適當的值。

public class test 
{ 
    private string[] _textBoxes; 

    // constructor 
    public test() 
    { 
     _textBoxes = new string[30]; 
    } 

    // bind your textboxes to a bunch 
    // of properties 
    public string Property0 
    { 
     get 
     { 
      return _textBoxes[0]; 
     } 
     set 
     { 
      _textBoxes[0] = value; 
      OnPropertyChanged("Property0"); 
     } 
    } 
} 
0

難道你不能讓數組全局化爲表單而不是局部到方法嗎?這樣你只能創建一次數組(也許在表單的Load()事件中)。

如果使控件數組全球是不是一種選擇,你可以通過名稱查找的控件(雖然這是比你的陣列的方法有點慢)

string idx = (selection + 1).ToString(); // convert selection to 1-based index string 

TextBox subjectText = (TextBox)FindControl("textBox" + idx); 
TextBox amtCreditsText = (TextBox)FindControl("textBox1" + idx); 
TextBox marksText =  (TextBox)FindControl("textBox2" + idx); 
相關問題