2009-06-07 66 views
0

我已經獲得了工作代碼,因此當我按下按鈕「添加更多」時,它將更多組合框添加到名稱爲dayBox1,dayBox2等的窗體中。從動態添加的組合框打印數據?

這是該代碼:

 private void addMoreBtn_Click(object sender, EventArgs e) 
    { 
     //Keep track of how many dayBoxes we have 
     howMany++; 

     //Make a new instance of ComboBox 
     ComboBox dayBox = new System.Windows.Forms.ComboBox(); 

     //Make a new instance of Point to set the location 
     dayBox.Location = new System.Drawing.Point(Left, Top); 
     dayBox.Left = 13; 
     dayBox.Top = 75 + dayLastTop; 

     //Set the name of the box to dayBoxWhateverNumberBoxItIs 
     dayBox.Name = "dayBox" + howMany.ToString(); 

     //The TabIndex = the number of the box 
     dayBox.TabIndex = howMany; 

     //Make it visible 
     dayBox.Visible = true; 

     //Set the default text 
     dayBox.Text = "Pick One"; 

     //Copy the items of the original dayBox to the new dayBox 
     for (int i = 0; i < dayBoxO.Items.Count; i++) 
     { 
      dayBox.Items.Add(dayBoxO.Items[i]); 
     } 

     //Add the control to the form 
     this.Controls.Add(dayBox); 

     //The location of the last box's top with padding 
     dayLastTop = dayBox.Top - 49; 
    } 

什麼是打印與按鈕事件加入盒中的所選成員的最好方法?

我打印,我想一個文件中的信息是這樣的前(從只有一個框)的方式:

public void saveToFile() 
     {  
      FileInfo t = new FileInfo("Workout Log.txt"); 
      StreamWriter Tex = t.CreateText(); 
      Tex.WriteLine("---------------Workout Buddy Log---------------"); 
      Tex.WriteLine("------------------- " + DateTime.Now.ToShortDateString() + " ------------------"); 
      Tex.Write(Tex.NewLine); 
      if (dayBoxO.Text != "Pick One") 
      { 
       Tex.WriteLine("Day: " + dayBoxO.Text); 
      } 
      else 
      { 
       Tex.WriteLine("Day: N/A"); 
      } 
     } 

我希望能夠爲每個盒子做到這一點,每一個新的線。所以,它會是這樣的: 日:(box1的文字) 日:(box2的文字) 日:(文字框3) 等等...... 謝謝!

回答

2

兩種方式我立即看到你可以這樣做:

首先是要保持引用到這些控件列表,當你加入他們。

private List<ComboBox> _comboBoxList = new List<ComboBox>(); 

... 

//Make a new instance of ComboBox 
ComboBox dayBox = new System.Windows.Forms.ComboBox(); 

//Add your combobox to the master list 
_comboBoxList.Add(dayBox); 

... 

那麼你的SaveToFile()方法將包含看起來是這樣的一行:

foreach(var box in _comboBoxList) 
{ 
     Tex.Write(Tex.NewLine); 
     if (box.Text != "Pick One") 
     { 
      Tex.WriteLine("Day: " + box.Text); 
     } 
     else 
     { 
      Tex.WriteLine("Day: N/A"); 
     } 
} 

第二種方法是做的Mike指出,步行的控件列表尋找你的組合框。

2

假設控制現場的形式,通過所有的窗體上的控件走:

var boxes = from Control c in this.Controls 
      where c.GetType() == typeof(System.Windows.Forms.ComboBox) 
      select c; 

StringBuilder sb = new StringBuilder(); 
foreach (Control c in boxes) 
{ 
    sb.AppendLine(c.Text); // ... 
} 

非LINQ的方法:

StringBuilder sb = new StringBuilder(); 
foreach (Control c in this.Controls) 
{ 
    if (c.GetType() == typeof(System.Windows.Forms.ComboBox)) 
    { 
     sb.AppendLine(c.Text); // ... 
    } 
} 

這是一個有點哈克依靠Controls集合但是,特別是當你開始使用面板和其他分組時。正如喬希所建議的那樣,您可以考慮將控件添加到您自己的收藏中。