"Add More"ボタンを押すと、フォームに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;
}
何?
私は前のファイルに欲しかった情報を印刷した方法は、(1つのボックスだけから)このようなものだった:
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");
}
}
私はすべての箱のためにこれを行うことができるようにしたい、それぞれの新しい上ライン。 日:(ボックス1のテキスト) 日:(ボックス2のテキスト) 日:(ボックス3のテキスト) など... ありがとう!
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コレクションに頼らざるを少しハックのコントロールを想定し