Question:
C# Windows Forms How do I pass values between 2 usercontrols?
automicss
2009-06-24 04:25:34 UTC
How do I pass values between 2 usercontrols in C# windows forms?
This is the situation:
In usercontrol1 I got a textbox and a button
In usercontrol2 I got a listview
Now I want to add the text from the texbox in usercontrol1 to the listview in usercontrol2.

Please help me out !
P.S.
I know how to pass values between forms, but this is between user controls.
Three answers:
Thinking.
2009-06-24 04:46:01 UTC
Hi, Why you want to transfer values between user controls. to fulfill your requirement rather then doing a dirty way? you can do something like this:



1. Create an event in your usercontrol1 like OnCommand and get return a userdefine object containing your values of your textboxes while raising your event.



2. Make a property in your usercontrol2 that accept your user define object and and setup your ListView.



Now you have to call usercontrol2's property/method by passing usercontrol1's object that comes from the event.



However if still you wish to do the dirty way then what you can do is search control from Parent window like below:



UserControl1 MyControl = Parent.Controls.Find("yourcontrol name", false);



and then setup MyControl however you wants.



One more thing you can do

foreach (UserControl1 MyControl in Parent.Controls)

{

// setup MyControl



}





All the best!
2009-06-24 11:54:50 UTC
Typically you pass between controls via the form itself.



If you want to pass between controls than

1) You have to create your own subclass of controls. You have to change the form coding to create the control based on your classes.

2) Both subclasses must have a method to have each other's object

3) The form must pass the object to each of the subclasses.

4) You have to process the appropriate event in the subclass (e.g., text changed event) to pass the data along.
mahmoud_wow
2009-06-24 11:37:37 UTC
You Can do it via Add Method of Items Collection of ComboBox:

comboBox1.Items.Add(Object item);

Ex.:

add this code to Button_Click Event Handler



private void button1_Click(object sender, EventArgs e)

{



comboBox1.Items.Add(textBox1.Text);

}

Buy.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...