2017-12-21 9 views
0

こんにちは私はこのコードを短くしたい:このタイプのコードをC#で短くするには?

tb1n.Text = Settings2.Default.tb1n; 
tb2n.Text = Settings2.Default.tb2n; 
tb3n.Text = Settings2.Default.tb3n; 
tb4n.Text = Settings2.Default.tb4n; 
tb5n.Text = Settings2.Default.tb5n; 
tb6n.Text = Settings2.Default.tb6n; 
tb7n.Text = Settings2.Default.tb7n; 
tb8n.Text = Settings2.Default.tb8n; 
tb9n.Text = Settings2.Default.tb9n; 
tb10n.Text = Settings2.Default.tb10n; 
tb11n.Text = Settings2.Default.tb11n; 
tb12n.Text = Settings2.Default.tb12n; 
tb13n.Text = Settings2.Default.tb13n; 

後、私はロードするために、より多くの設定が追加されますし、私はそれを短くする必要がありますが、私は方法を知っているドント。

私はこのような文字列にこのコードを取得しようとしました:

int i = 1; 
do 
{ 
    string tbload = "tb" + i + "n.Text = Settings2.Default.tb" + i + "n"; 
    i++; 
} while (i == 13); 

しかし、文字列からコードを実行することはないと私はそれのようドントするのは難しいですので、私はこれは良い解決策ではありません実現しています。

+5

なぜこのような質問が頻繁にここに表示されますか?それらが似ている場合は、リストや表形式のデータを表示するコントロールとコントロールを使用します。彼らが似ていない場合は、意味のある名前を付けてください。 2日前の同様の質問:https://stackoverflow.com/questions/47882933/c-sharp-enabling-button-using-datatable-for-loop/47883276#47883276その他2日前に回答済み:https://stackoverflow.com/question/47883307/check-for-if-if-if-if-checkbox/47883371#47883371 –

+3

13の代わりにコントロールのリスト*を使用しないのはなぜですか?次に、インデックスiの要素の値を簡単に設定できます。 – HimBromBeere

答えて

2

視覚的なツリーヘルパークラスを作成し、表示されているすべてのテキストボックスインスタンスを見つけることができます。

ヘルパークラス:あなたはこのようなリストにあなたのTextBoxとあなたの文字列を格納することができます

public static class TreeHelper 
    { 
     public static IEnumerable<T> FindVisualChildren<T>(this DependencyObject depObj) where T : DependencyObject 
     { 
      if (depObj == null) yield break; 

      for (var i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) 
      { 
       var child = VisualTreeHelper.GetChild(depObj, i); 
       var children = child as T; 
       if (children != null) 
        yield return children; 

       foreach (T childOfChild in FindVisualChildren<T>(child)) 
        yield return childOfChild; 
      } 
     } 
    } 

コール

var children = this.FindVisualChildren<TextBox>(); 
foreach (var child in children) 
{ 
    child.Text = Settings.Default[child.Name].ToString(); 
} 
1

 List<TextBox> TextBoxes = new List<TextBox>() { 
      tb1n, 
      tb2n, 
      tb3n, 
      ... 
     }; 

     List<string> mySettings = new List<string>(){ 
      Settings2.Default.tb1n, 
      Settings2.Default.tb2n, 
      Settings2.Default.tb3n, 
      ... 
     }; 

     foreach (TextBox item in TextBoxes) 
     { 
      item.Text = mySettings[TextBoxes.FindIndex(a => a.Name == item.Name)]; 
     } 

そしてあなたforeachループを使うことができます。すべてのTextBoxにTextプロパティ値を与えます。

関連する問題