m having problem in operating on richtextbox from another class
m using backgroundworker class to seperate GUI thread from the computation thread
this is the function i need to call from other class
public void UpdateRTB(String strText, Color colVar)
{
if (InputBox.InvokeRequired)
{
InputBox.Invoke(new UpdateRTBCallback(this.UpdateRTB), new object[] { strText, colVar });
}
else
{
InputBox.Select(InputBox.Text.IndexOf(strText), strText.Length);
InputBox.SelectionColor = colVar;
InputBox.Update();
}
}
the variable objForm1 is the variable declared after initialization of the form as
objForm1 = this;
the function which return the form is
public static Form1 GetThisForm()
{
return objForm1;
}
this is my delegate which is declared globally
public delegate void UpdateRTBCallback(String strText, Color strColor);
this is the code m writing in another class to call it
Form1 form1 = Form1.GetThisForm();
form1.UpdateRTB(item, Color.Yellow);
in the objForm1, when I debug I see the fields of it is showing System.InvalidOperationException.. is this the problem of I’m doing something wrong
Please help!!!
OK, I’m guessing there’s a second possible scenario. The reference to your form gets set after initialization of the form so I guess that’s in your form constructor (and I hope it’s after InitializeComponent() according to the WinForms guidelines..). The function that returns the reference is static, which means the reference also has to be static, which means you could be looking at it before the constructor of the form got called and before the reference got set. Here I’ll have to add you did not show us where you are accessing the reference from (from a (static) function that ran before the form got constructed?).
Anyway, here are some alternatives I’m hoping will be a useful answer / option to you -> instead of writing your own you may want to have a look at these useful helper properties that seem to already do what you need Form.ActiveForm or Application.OpenForms.
PS: System.InvalidOperation may show up for your form’s fields because they too are being evaluated from another (debug) thread than the UI thread.