父表单无法访问子表单公共属性 - Winforms c#

时间:2022-09-02 12:35:45

I am feeling kind of stupid at the moment, because everywhere I read this is a normal procedure, and I just cannot find why I am not able to do it also!

我此刻感觉有点愚蠢,因为我读到的每个地方都是正常程序,而我也无法找到为什么我也无法做到这一点!

So, the situation is the following, I have a Parent Form and a Child Form. The Child Form has a public property. From the Parent Form, i want to access the Child Form public property, and I can't.

所以,情况如下,我有一个父表和一个子表。儿童表格有公共财产。从父表单,我想访问子表单公共属性,我不能。

My code is the following:

我的代码如下:

Parent code:

父代码:

namespace myProgram.UserInterfaces
{
  public partial class ProjectNew : Form
  {
    public ProjectNew()
    {
        InitializeComponent();
    }

    private void ButtonSelectCustomer_Click(object sender, EventArgs e)
    {
        using (Form f = new ProjectCustomerList())
        {
            this.SuspendLayout();
            f.ShowDialog(this);
        }
        this.Show();
    }
  }
}

Child code:

子代码:

namespace myProgram.UserInterfaces
{
  public partial class ProjectCustomerList : Form
  {
    public EntCustomer _selectedCustomer = new EntCustomer();

    public EntCustomer SelectedCustomer {
        get
        {
            return _selectedCustomer;
        }
    }

    public ProjectCustomerList()
    {
        InitializeComponent();
    }
    // --- other code ---
  }  
}

After the using (Form f = new ProjectCustomerList()) i would like to do the following: var sCustomer = f.SelectedCustomer;, but when I do this, Visual Studio doesn't recognize the Child Form public property.

在使用之后(Form f = new ProjectCustomerList())我想执行以下操作:var sCustomer = f.SelectedCustomer;,但是当我这样做时,Visual Studio无法识别Child Form公共属性。

What am I doing wrong? :|

我究竟做错了什么? :|

1 个解决方案

#1


3  

This is normal with inheritance, since f in your case is handled as a simple Form.

这对于继承来说是正常的,因为在你的情况下f被处理为一个简单的Form。

You could typecast it to ProjectCustomerList to access the Property. The is operator is also useful.

您可以将其类型转换为ProjectCustomerList以访问该属性。运算符也很有用。

if (f is ProjectCustomerList)
{
    (f as ProjectCustomerList).SelectedCustomer =...;
}

or simply

或简单地说

using (ProjectCustomerList f = new ProjectCustomerList())
{
    f.SelectedCustomer =...;
}

seen var in other comments, works too

在其他评论中看到var,也有效

using (var f = new ProjectCustomerList())
{
    f.SelectedCustomer =...;
}

#1


3  

This is normal with inheritance, since f in your case is handled as a simple Form.

这对于继承来说是正常的,因为在你的情况下f被处理为一个简单的Form。

You could typecast it to ProjectCustomerList to access the Property. The is operator is also useful.

您可以将其类型转换为ProjectCustomerList以访问该属性。运算符也很有用。

if (f is ProjectCustomerList)
{
    (f as ProjectCustomerList).SelectedCustomer =...;
}

or simply

或简单地说

using (ProjectCustomerList f = new ProjectCustomerList())
{
    f.SelectedCustomer =...;
}

seen var in other comments, works too

在其他评论中看到var,也有效

using (var f = new ProjectCustomerList())
{
    f.SelectedCustomer =...;
}