Another event handling question

I have the same issue as this guy does: http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=127763&SiteID=1

I have searched my local 2005 MSDN here: ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_csref/html/804cecb7-62db-4f97-a99f-60975bd59fa1.htm

but there was never any usable answer to the question of splitting event handlers into other classes. I have a default Windows App that has a button and text box. When I press the button, I want the text "Hello World!" to appear in the text box. Cheesy - yes I know. I am trying to understand partial classes in the exercise. I want to split my event handlers so they are in other classes. This is my code:

namespace WindowsApplication1

{

public class Form1 : System.Windows.Forms.Form

{

...

this.button1.Location = new System.Drawing.Point(112, 8);

this.button1.Name = "button1";

this.button1.Size = new System.Drawing.Size(75, 23);

this.button1.TabIndex = 2;

this.button1.Text = "Click Me";

this.button1.Click += new System.EventHandler(this.button1_Click);

...

}

}

namespace WindowsApplication1

{

public partial class Class1 : Form1

{

private void button1_Click(object sender, EventArgs e)

{

this.textBox1.Text = "Hello World!";

}

}

}

When I compile this project, I get the following errors:

'WindowsApplication1.Form1' does not contain a definition for 'button1_Click'Error

'WindowsApplication1.Form1.textBox1' is inaccessible due to its protection level

I would like to leave the VS-generated event handler code alone (i.e. not mess with the protection level). Any suggestions

Oh yes - I apologize for the horrible HTML formatting. This editor won't let me keep my formatting!!



Answer this question

Another event handling question

  • matthijsbonte

    OK - that was the problem. This is the correct code:
    

    namespace WindowsApplication1

    {

    public partial class Form1 : System.Windows.Forms.Form

    {

    private void button1_Click(object sender, EventArgs e)

    {

    this.textBox1.Text = "Hello World!";

    }

    }

    }

    The amazing thing about partial classes is that I can now break my even handlers up into managable files! Awesome! Thank you for your help!!


  • MKeeper

    Both of the class definitions need to have the partial keyword. Without it, when the compiler looks for button1_Click, it doesnt know that there are other places to look for it.

  • TeddyG

    Change class definition of both 'parts' to:

    public partial class Form1 : System.Windows.Forms.Form

    In your code the Class1 is derived from Form1 and not a 'part' of it.



  • Another event handling question