Wednesday, December 9, 2009

Accessing control from another form in C#.NET

Say you have two forms(Form_One and Form_Two) in your project. Suppose Form_One contains SplitContainer control. Now you want to use the SplitContainer control object into the Form_Two. How? The solution is as follows.

At first you have to declare the SplitContainer control object as public instead private in the Form_One.Designer.cs as bellow.

public System.Windows.Forms.SplitContainer splitContainer1;


Then you have to create Form_Two object and call Form_Two from Form_One class using the following code.

Form_Two frmTwo = new Form_Two(this);
frmTwo.Show();

Then you can get the SplitContainer control object in the Form_Two using the following code.

public partial class Form_Two : Form
{
public Form_Two()
{
InitializeComponent();
}
private void BtnSplitCtr _Click(object sender, EventArgs e)
{
splitContainer1.Panel2.Controls.Clear();
}
}

However, the above code is not enough. You have to modify the Form_Two class as bellow. Otherwise NullReferenceException(Object reference not set to an instance of an object) can be occurred. The modified code is given bellow.

public partial class Form_Two : Form
{
private Form_One frmOne;
public Form_Two(Form_One frm)
{
InitializeComponent();
frmOne = frm;
}
private void BtnSplitCtr _Click(object sender, EventArgs e)
{
frmOne.splitContainer1.Panel2.Controls.Clear();
}
}

That's it.

No comments:

Post a Comment

Related Posts with Thumbnails