Monday, May 24, 2010

Visual C# question?

I have a MDI child form with a RichTextBox, on the KeyDown event of the RichTextBox I want to display the current line number on a ToolStripStatus label, that is located on a StatusStrip on the PARENT form.





my question is: how to make a reference to the parent form so I can change the Text property of the label





if i do





Form1 theParentForm = new Form1();





i create another object, and i can modify its properties, but not the original form

Visual C# question?
Normally this sort of reference passing would happen in the constructor. But since you make be working with a pre-defined constructor, you'd have to manually set it.





You'll need to extend the Form class for your child window class, if you're not already. You'd do it like this:





class ChildForm : Form


{


// Then, inside this new class, have a variable like this:


private Form1 parentForm = null;





//...and a method like this:


public void SetParentForm(Form1 refParentForm)


{


parentForm = refParentForm;


}


}





After you create the child form, also call this new method (from within the parent form code):





E.g.


ChildForm childForm1 = new ChildForm();


childForm1.SetParentForm(this);








Next, in order to access the toolstrip on the parent form, you'll earlier need to make the statusStrip public (which violates Object-Oriented encapsulation -- i.e. bad idea), or make a public method which sets the statusStrip for you:





E.g. (in ParentForm)





public void SetStatusStripText(string text)


{


statusStrip.Text = text;


}








Finally, in your click event of the child form:


{


parentForm.SetStatusStripText( ....line number.... );


}





Cheers.


No comments:

Post a Comment