2016-03-24 1 views
0

とラベルをループ:は、私は、テキストファイルに書かれているものに応じて、いくつかのラベルの背景を変更したい似た名前のC#

private void Form3_Load(object sender, EventArgs e) 
     { 
      string[] words = new string[7]; 
      StreamReader read = new StreamReader(path); 
      while(!read.EndOfStream) 
      { 
       string line = read.ReadLine(); 
       words = line.Split(';'); 
       if(words[6] == "no") 
       { 
        //-----What I have to write here--- 
       }    
      } 
      read.Close(); 
     } 

「lbl101」、「lbl102」という名前の50枚のラベルの上にあり、 」.... "" lbl150"

+0

は、私が何をその明確ではないと思いますあなたの求める。あなたはどのような条件でラベル付けしたいですか? – Johannes

+0

それらをすべてスタックに置き、色を変更しますか? –

答えて

1

作業溶液あります:

private void Form3_Load(object sender, EventArgs e) 
     { 
      int count = 101; 
      string[] words = new string[7]; 
      StreamReader read = new StreamReader(pathRooms); 
      while(!read.EndOfStream) 
      { 
       string line = read.ReadLine(); 
       words = line.Split(';'); 
       if (words[6] == "no") 
       { 

         Label currentLabel = (Label)this.Controls.Find("lbl" + count, true)[0]; 
         currentLabel.BackColor = Color.Yellow; 

       } 
       count = count + 1; 
      } 
      read.Close(); 
     } 
1

はそれを試してください:

if(words[6] == "no") 
{ 
    int count = 150; 
    for (int a = 1 ; a < count; a++) 
    { 
     Label currentLabel = (Label)this.Controls.Find("lbl"+a,true)[0];  
     //change color of currentLabel 
    } 
} 
+0

それは動作しません、System.Windows.Form.Controls []をSystem.Windows.Form.Labelに変換することはできません – Vexorei

+0

編集した回答を参照してください、[0]を追加しました –

+0

ありがとうございました!それは最終的に動作します! – Vexorei

1

あなたが好きな形のControlsコレクションでOfType<T>()方法を使用して、すべてのそれらを反復処理することができます:

if(words[6] == "no") 
{ 
    foreach(var label in this.Controls.OfType<Label>().Where(x=>x.Name.Contains("lbl"))) 
    { 
     label.Text = "Some Text"; 
    } 
} 

これは、他のユーザーコントロールまたはネストされたパネル内にネストされたラベルがそのyou have to do it recursivelyため、影響を受けません、フォームの直接の子ですラベルに動作します。

+0

ポストへのリンクありがとう –

0

LabelオブジェクトのフォームチェックのControlsコレクションをループします。それに応じて、指定された値に従って修正します。

0

1.)すべてのラベルを含むリストを作成します。

Label lbl101 = new Label(); 
Label lbl102 = new Label(); 
... 

List<Label> labels = new List<Label>() 
{ 
    lbl101, 
    lbl102 
... 
}; 

2)あなたの言葉は、[]の文字列は、あなたが書くことができ、色の名前である場合:

if(words[6] == "no") 
{ 
    System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml(words[..]); 
    foreach(Label l in Labels) 
    { 
     l.BackColor = myColor; 
    } 
} 
関連する問題