I want to refer control from previous page in windows form application. On the form1 i have a textbox1 and listbox1 and form2 contain two label as label1 and label2. On the loading of form2 i want display the result of textbox1 on label1 and the result of listbox1 on label2.
I tried below code :
------------------------------------Form-1----------------------------------------------
namespace msg
{
public partial class ToReferControlFromPrevPage_prev_page_ : Form
{
public ToReferControlFromPrevPage_prev_page_()
{
InitializeComponent();
}
//private void ToReferControlFromPrevPage_prev_page__Load(object sender, EventArgs e)
public void ToReferControlFromPrevPage_prev_page__Load(object sender, EventArgs e)
{
listBox1.Items.Add("Emp id : a_108");
listBox1.Items.Add("Age 24");
listBox1.Items.Add("Post: Developer");
listBox1.Items.Add("mob : 9977668018");
listBox1.Items.Add("Add : Indore");
}
//private void textBox1_TextChanged(object sender, EventArgs e)
public void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
----------------------------------------Form-2------------------------------------------
namespace msg
{
public partial class ToReferControlFromPrevPage_next_page_ : Form
{
public ToReferControlFromPrevPage_next_page_()
{
InitializeComponent();
}
private void ToReferControlFromPrevPage_next_page__Load(object sender, EventArgs e)
{
ToReferControlFromPrevPage_prev_page_ p1 = Application.OpenForms ["ToReferControlFromPrevPage_prev_page_"] as ToReferControlFromPrevPage_prev_page_;
label1.Text = p1.textBox1.Text;
}
}
}
VulpesPosted Mar 13, 2013, 5:03 PM
To deal with the ListBox, you'd need this code:
if (p1.listBox1.SelectedIndex > -1)
{
label2.Text = p1.listBox1.SelectedItem.ToString();
}
else
{
label2.Text = "";
}
Vishal GilbilePosted Mar 13, 2013, 10:14 PM
As per my suggestion what you can do is in your form2 create a constructor which accepts two arguements. So your code for form2 will be somewhat like the following
public class Form2:Form
{
private string _val1,_val2;
public Form2()
{
//Default Constructor
}
public Form2(string value1,string value2)
{
//Set the value of value1 and value2 to the class level variables of your form2
}
}
And finally when you are creating the instance of form2 in your form1 class try to call your this constructor, like the following.
Form2 objForm2=new Form2(txtTextBox1.Text,ListBox1.SelectedItem.Text);
Hope that solves your problem.
With Regards,
Vishal Gilbile.