Hi, I have a form in c# with a multiline textInput which content I need to be updated form an object outside the form. How can I achieve this ? Using events ? Passing the textInput to the object's contructor ?
Thanks in advance.
Hi, I have a form in c# with a multiline textInput which content I need to be updated form an object outside the form. How can I achieve this ? Using events ? Passing the textInput to the object's contructor ?
Thanks in advance.
Hi, i would not pass the text to the object. If you just need it as initialization value, passing the text to the constructor of the form would be fine. But not other way round.
Very simple solution: Give your form a public SetTextValue(string Text) method, that sets the text.
Events will work also, but seems a bit overpowered for such a simple problem.
There are a lot of ways to accomplish this depending on the specifics of what you're working on.
Update the text field from within the form?
txtField.Text = someObject.SomeProperty;
Set the value in the form's constructor?
SomeFormClass form1 = new SomeFormClass(aString);
form1.Show();
Call a method on the form from an external object?
public void SetText(string text) { txtField.Text = text; }
form1.SetText(aString);
Use data binding?
txtField.DataBindings.Add(new Binding("Text", someObject, "SomeProperty");
It's hard to answer without knowing more details.
Have a look at the MVP pattern - you could have your form implement an IView interface. Your other object would be the Presenter that would call, for example, IView.UpdateText() when something changes (or have your view subscribe to the presenters events - i prefer the method approach).
This separates your concerns and makes your solution more testable as you can mock up implementations of IView, IPresenter and IModel.
The form should check if this.InvokeRequired == true
to determine if the incoming request is on the UI thread. If it is not you will need to use a delegate.
public delegate void UpdateTextDelegate(string text);
public void UpdateText(string text)
{
// Check we are on the right thread.
if (!this.InvokeRequired)
{
// Update textbox here
}
else
{
UpdateTextDelegate updateText = new UpdateTextDelegate(this.UpdateText);
// Executes a delegate on the thread that owns the control's underlying window handle.
this.Invoke(updateText, new object[] { text });
}
}