我已经让代码工作了,所以当我按下按钮“添加更多”时,它会在表单中添加更多的组合框,名称为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的文字) 日:( box3的文字) 等等... 谢谢!
答案 0 :(得分: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系列有点笨拙;特别是当你开始有面板和其他分组时。您可以考虑将控件添加到您自己的集合中,正如Josh建议的那样。
答案 1 :(得分: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指出并走控制列表寻找你的组合框。