我可以在当前类之外调用控件,但不能操作

时间:2017-02-12 18:06:58

标签: c# combobox

我有两个课程。我的目标是更改组合框的数据源但是我首先测试了我是否可以看到组合框有多少项只是但我无法做到。我能够在当前之外调用一个ComboBox类似:

public partial class secondclass: Form
{
      public secondclass()
      {
           firstclass first=new firstclass();
           MessageBox.Show(first.comboBox1.Items.Count.ToString())//it gives 0 item 
           //even if i have 5 items.
      }

}
public partial class firstclass: Form
{.....
}

1 个答案:

答案 0 :(得分:1)

您在此处firstclass first=new firstclass();实例化了新表单。 你需要有一个指向现有表单的指针,comboBox被填充而不是新的表空。在实例化第二个类时,将第一个类的指针发送到第二个类,如下所示:

public partial class secondclass: Form
{
      public secondclass(firstclass first)
      {
           // firstclass first=new firstclass();
           MessageBox.Show(first.comboBox1.Items.Count.ToString())
      }

}
public partial class firstclass: Form
{
    private void button1_Click(object sender, EventArgs e)
    {
        secondclass second = new secondclass(this); // Pointer to first class
    }
}