Tramyer
Tramyer

Reputation: 13

How to re-enable buttons from Mainform to another form?

How do I re-enable a button from Form1 to Form2.

The button is currently in Form1 but I need it to re-enable in Form2.

Please see below my code :

public partial class Form2 : Form
{

    public const int WM_NCLBUTTONDOWN = 0xA1;
    public const int HTCAPTION = 0x2;


    public object Form1 { get; private set; }

    [DllImport("User32.dll")]
    public static extern bool ReleaseCapture();

    [DllImport("User32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

    public Form2()
    {
        InitializeComponent();
    }

    private void Label_XButton2_Click(object sender, EventArgs e)
    {
        Form1.button1.Enabled = true;
    }

I did add the "public form 1" still it doesn't allow me to do what i want it to do.

Upvotes: 0

Views: 112

Answers (2)

Nino
Nino

Reputation: 7115

Your Form2 doesn't "know" for an instance of Form1. In other words, it doesn't know it exists. Pass instance of Form1 to Form2 via property or constructor. This is second approach:

make sure you have property in Form2

public partial class Form2 : Form
{
    public const int WM_NCLBUTTONDOWN = 0xA1;
    public const int HTCAPTION = 0x2;

    //you already have property, that's good! :)
    public Form1 Form1 { get; private set; } 

    //rest of Form2 code...

change Form2 constructor like this, to enable passing instance to Form2

public Form2(Form1 frm)
{
    InitializeComponent();
    //"save" instance in property
    this.Form1 = frm;
}

On Form1, when instatiating Form2, pass it reference to Form1, like this:

Form2 frmTwo = new Form2(this); //"this" is Form1, passed as constructor's param.
frmTwo.Show();

Later, when you need to access something, like that button, you can to it like this:

private void Label_XButton2_Click(object sender, EventArgs e)
{
   this.Form1.button1.Enabled = true;
}

Upvotes: 1

Mong Zhu
Mong Zhu

Reputation: 23732

here is a recipe:

1) change this line

public object Form1 { get; private set; }

to be of type Form1

public Form1 internalForm1 { get; private set; }

2) make a second constructor that takes a Form1 as parameter:

public Form2(Form1 f1) : this()
{
    internalForm1 = f1;
}

3) pass the current instance of Form1 into the constructor of Form2 when you create it in Form1

Form2 f2 = new Form2(this)

4) make a method in Form1 that does the changes

public void ChangeButtonStatus()
{
    this.button1.Enabled = !this.button1.Enabled;
}

4) and call this method in Form2:

private void Label_XButton2_Click(object sender, EventArgs e)
{
    internalForm1.ChangeButtonStatus(); 
}

this will flip the button

Upvotes: 2

Related Questions