无法控制。在GroupBox中找到一个ComboBox

时间:2015-11-05 02:02:21

标签: c# winforms combobox groupbox

在我的Visual C#Form应用程序中,我在组合框中有一个组合框,以帮助整理/看起来整洁。但是,一旦我将组合框放在组合框中,我就无法通过循环遍历表单上的所有控件来找到它。

例如,如果我在Groupbox中使用Combobox运行此代码,我得到的结果与在组框外部的结果不同:

  foreach (Control contrl in this.Controls)
  {
       richTextBox1.Text += "\n" + contrl.Name;
  }    

如果组合框位于组框内,则无法找到它。

我还注意到在Form1.Designer.cs文件中,每当我在组合框中添加组合框时,组框中会出现以下代码行:

this.groupBox4.Controls.Add(this.myComboBox);
..
this.groupBox4.Location = new System.Drawing.Point(23, 39);
this.groupBox4.Name = "groupBox4";
... etc...

此行将被删除:

this.Controls.Add(this.myComboBox);

如果我尝试手动编辑它,一旦我将组合框移回组合框内,它会自动切换回来。

任何帮助将不胜感激!谢谢!

布赖恩

4 个答案:

答案 0 :(得分:1)

正如您所说,您将组合框添加到组框中,因此它会添加到组Controls组框中,设计人员会生成此代码:

this.groupBox4.Controls.Add(this.myComboBox);

因此,如果您想以编程方式找到组合框,可以使用以下选项:

  • 为什么不简单地使用:this.myComboBox
  • 使用var combo = (ComboBox)this.Controls.Find("myComboBox", true).FirstOrDefault();
  • 使用var combo = (ComboBox)this.groupBox4.Controls["myComboBox"]

此外,如果你想要循环,你应该使用:

循环this.groupBox4.Controls
  • foreach(Control c in this.groupBox4.Controls) {/*use c here */}
  • this.groupBox4.Controls.Cast<Control>().ToList().ForEach(c=>{/*use c here */})

答案 1 :(得分:0)

就像Form对象一样,Group对象可以包含一组控件。您需要遍历Group控件的控件集合。

答案 2 :(得分:0)

在GroupBox中获取所有或一个ComboBox的另一个想法,在本例中为groupBox1。 Resate Resa建议使用Find with FirstOrDefault最好访问一个组合框。

List<ComboBox> ComboBoxes = groupBox1
    .Controls
    .OfType<ComboBox>()
    .Select((control) => control).ToList();

foreach (var c in ComboBoxes)
{
    Console.WriteLine(c.Name);
}

string nameOfComboBox = "comboBox1";
ComboBox findThis = groupBox1
    .Controls
    .OfType<ComboBox>()
    .Select((control) => control)
    .Where(control => control.Name == nameOfComboBox)
    .FirstOrDefault();

if (findThis != null)
{
    Console.WriteLine(findThis.Text);
}
else
{
    Console.WriteLine("Not found");
}

答案 3 :(得分:0)

您可以使用ControlCollections Find方法,它有一个参数可以搜索父级及其子级以供您控制。

ComboBox temp;
Control[] myControls = Controls.Find("myComboBox", true); //note the method returns an array of matches
if (myControls.Length > 0) //Check that it returned a match
    temp = (ComboBox)myControls[0]; //use it
相关问题