null reference problems with c#
Posted
by alex
on Stack Overflow
See other posts from Stack Overflow
or by alex
Published on 2010-05-18T21:17:29Z
Indexed on
2010/05/18
21:20 UTC
Read the original article
Hit count: 139
c#
Hi:
In one of my window form, I created an instance of a class to do some works in the background. I wanted to capture the debug messages in that class and displayed in the textbox in the window form. Here is what I did:
class A //window form class
{
public void startBackGroundTask()
{
B backGroundTask = new B(this);
}
public void updateTextBox(string data)
{
if (data != null)
{
if (this.Textbox.InvokeRequired)
{
appendUIDelegate updateDelegate = new appendUIDelegate(updateUI);
try
{
this.Invoke(updateDelegate, data);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
else
{
updateUI(data);
}
}
}
private void updateUI(string data)
{
if (this.Textbox.InvokeRequired)
{
this.Textbox.Invoke(new appendUIDelegate(this.updateUI), data);
}
else
{
//update the text box
this.Textbox.AppendText(data);
this.Textbox.AppendText(Environment.NewLine);
}
}
private delegate void appendUIDelegate(string data);
}
class B // background task
{
A curUI;
public b( A UI)
{
curUI = UI;
}
private void test()
{
//do some works here then log the debug message to UI.
curUI.updateTextBox("message);
}
}
I keep getting a null reference exception after this.Invoke(updateDelegate, data); is called.
I know passing "this" as a parameter is strange. But I want to send the debug message to my window form.
Please help.
Thanks
© Stack Overflow or respective owner