Jakob Busk Sørensen
Jakob Busk Sørensen

Reputation: 6091

Call public property from partial class

I have a public property in a partial class (UserControl) which I would like to access from another partial class (Form). However I cannot call this property, even though it is public. They are located in the same namespace, so this should not be the issue.

Partial Class #1 (User Control)

public partial class MyUserControl : UserControl
{
    // This is the value I want to read from the main form
    public String MyVariableValue
    {
        get { return cboMyComboBox.Text; }
    }
}

Partial Class #2 (Main Form)

public partial class MyForm : Form
{
    // This function should show a message box with the value
    private void ShowMyVariable()
    {
        MessageBox.Show("You have selected: " + MyUserControl.MyVariableValue);
    }
}

Error code:

CS0119 'MyForm' is a type, which is not valid in the given context

Update: I had a lot of errors in the original code which has been corrected. It is two different forms, that was not clear before, sorry...

Upvotes: 0

Views: 735

Answers (2)

AndersJH
AndersJH

Reputation: 142

After the changes to your post, I suggest the following: I assume the MyForm has an instance of the MyUserControl, which is necessary to show the usercontrol. Then you access the instance Change

MessageBox.Show("You have selected: " + MyForm.MyVariableValue);

to

MessageBox.Show("You have selected: " + _myUserControl.MyVariableValue);

where _myUserControl is the name of the instance variable of type MyUserControl. It is probably found in the other part of the MyForm class, the auto-generated part, and could look something like this:

MyUserControl _myUserControl = new MyUserControl();
this.Controls.Add(_myUserControl);

Upvotes: 2

Balaji Marimuthu
Balaji Marimuthu

Reputation: 2058

Access it this modifier

 private void ShowMyVariable()
    {
        MessageBox.Show("You have selected: " + this.MyVariableValue);
    }

Upvotes: 0

Related Questions