我试图找到当前foreach循环所在的位置,我可以根据其当前状态以不同方式处理foreach循环。如果它在groupbox1或groupbox2中。
int Name = 1;
string Usernames = @"C:\UPHhour\names.txt";
using (FileStream fs = new FileStream(Usernames, FileMode.Create, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
var Names = groupBox1.Controls.Cast<Control>().Concat(groupBox2.Controls.Cast<Control>());
foreach(Control OLR_FF in Names.Cast<Control>().OrderBy(c => c.TabIndex))
{
if(!string.IsNullOrWhiteSpace(OLR_FF.Text.ToString()))
{
//if the foreach loop is in groupbox1
if(OLR_FF is groupbox1)
{
//do something
}
// or if its in groupbox2
if(OLF_FF is groupbox2)
{
//do something different.
}
//sw.WriteLine("Name"+ Name++ + "=" + OLR_FF.Text.ToString());
}
}
}
如何知道循环是在groupbox1中还是在groupbox2中?
答案 0 :(得分:0)
使用Control.Parent
属性,然后检查父级是否等于两个组框之一
if(!string.IsNullOrWhiteSpace(OLR_FF.Text.ToString()))
{
//if the foreach loop is in groupbox1
if(groupbox1.Equals(OLR_FF.Parent))
{
//do something
}
// or if its in groupbox2
else if(groupbox2.Equals(OLF_FF.Parent))
{
//do something different.
}
//sw.WriteLine("Name"+ Name++ + "=" + OLR_FF.Text.ToString());
}