0

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...

Jakob Busk Sørensen
  • 5,599
  • 7
  • 44
  • 96
  • You don't need to specify `MyForm` to access class member. When you specifiy class name the compiler will treat it as static member. – Hamlet Hakobyan Mar 07 '17 at 13:53
  • 3
    you could use `MyVariableValue` or `this.MyVariableValue` – Mike Mar 07 '17 at 13:54
  • 1
    That would only work if MyVariableValue were static. – Cleptus Mar 07 '17 at 13:59
  • @bradbury9 you seem to be on to something. However changing the property i Partial Class #1 isn't an option, since it cannot get its value from a combo box then...? – Jakob Busk Sørensen Mar 07 '17 at 14:02
  • 1
    Seems like you are using the class name MyUserControl instead of the instance name of MyUserControl. – Manish Mar 07 '17 at 14:25
  • @Manish I believe you are right. Now I just need to find a way to transfer the instance name to my display method. Or finding an entirely different way of accesing the combo box selection from outside the user control... – Jakob Busk Sørensen Mar 07 '17 at 14:27

2 Answers2

2

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);
AndersJH
  • 142
  • 1
  • 7
0

Access it this modifier

 private void ShowMyVariable()
    {
        MessageBox.Show("You have selected: " + this.MyVariableValue);
    }
Balaji Marimuthu
  • 1,940
  • 13
  • 13