Reputation: 815
I would like to update a TextBox
from an arbitrary form. Could you please suggest a way to do so?
Upvotes: 0
Views: 930
Reputation: 2353
You should take Jon's advice. The other way might be something as dirty as this:
// Bad practice
foreach (var child in theOtherForm.Controls){
if(child.Name == '_otherControlName')
{
(child as TextBox).Text = _thisTextBox.text;
}
}
You may need to check some types and some panel's child controls as well.
Upvotes: 0
Reputation: 1499770
Basically the same way you'd do anything with another object. You need to have a reference to the other form, and if it's a different type it has to expose the text box you're interested in as a property, or have a method to set the text. So for example, you might have:
public class FirstForm : Form
{
private TextBox nameInput;
public TextBox NameInput { get { return nameInput; } }
...
}
public class SecondForm : Form
{
private TextBox otherNameInput;
private FirstForm firstForm;
public void CopyValue()
{
firstForm.NameInput.Text = otherNameInput.Text;
}
}
Or putting the textbox responsibility in the first form:
public class FirstForm : Form
{
private TextBox nameInput;
public string Name
{
get { return nameInput.Text; }
set { nameInput.Text = value; }
}
...
}
public class SecondForm : Form
{
private TextBox otherNameInput;
private FirstForm firstForm;
public void CopyValue()
{
firstForm.Name = otherNameInput.Text;
}
}
There are various other ways to skin the cat, but those are the most common. How you get the reference to the FirstForm
into the SecondForm
will vary - it may be passed into the constructor for SecondForm
, or it could be created by SecondForm
itself. That will depend on the rest of your UI.
Note that this assumes the two forms use the same UI thread. It's possible (but relatively uncommon) to have different UI threads for different windows, in which case you'd need to use Control.Invoke
/BeginInvoke
.
Upvotes: 3
Reputation: 8653
Change the class and override the constructor of the form to pass in the data that you want. In the constructor store the varialble being passed in , into a member variable
Upvotes: 0