Search code examples
c#winformscontrolsinteraction

Interacting with a Windows control from another class C#


I am a C# newbie and have encountered the following problem.

I have a class called Form1 which contains a number of controls in design view.

I have another class called Staff which inherits from Form1 and which, amongst others, contains a method called PlayAll that plays all the music notes played by the user on a music keyboard one after the other.

In the method PlayAll, I have implemented a condition which determines whether a user pressed any notes or not.

If the user did not press any notes, an error message should be displayed in ErrorTextBox (contained in Form1.cs).

This is the relevant code of PlayAll() (in Staff.cs)

public void PlayAll()
{
    ErrorTextBox.Text = "";
    if (Pressed_Notes.Count == 0) //check if the user pressed a key
    {
        ErrorTextBox.Text = "There are no music notes to play!";
    }  
    else
    {
        //Play the music notes
    }
}

My problem is that nothing appears on the ErrorTextBox (found in Form1.cs). How can I solve this problem please? Thanks.


Solution

  • You can't access any form control from another class. The simple way to access them is unsafe way, here it is.. let suppose u have a class form1 which have a control Textbox1 and u have another class myClass. just pass the desired control as argument with ref. e.g.

    public Class myClass
    {
     TextBox tb;
     public myClass(ref TextBox mtb)
        {
         tb = mtb;
        }
     //...Now you can use tb as your textbox and the value in it will be 
     //...displayed on form1 control
    }
    
    public Class form1
    {
     myClass mc = new myClass(ref textBox1);
     // ...
    }
    

    But remember, its an unsafe operation to do so. This code will throw error in debugging mode. So run it without debugging..