Reputation: 35502
I can't believe it,this works in my other application,but in this one,which has similiar structure - it doesn't!
public string ListAdd
{
set
{
if (listView1.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
listView1.Items.Add(value);
});
}
else
{
listView1.Items.Add(value);
}
}
}
The way I call it:
var formz = Form.ActiveForm as Form1;
if (formz != null)
formz.ListAdd = "asdasdasdasd";
If I call it from the function where I receive packet(I want to put it on the listView) over TCP - Nothing happens,but If I call it in that same class where I initialize WinSock - it works.
Where could the problem be?
EDIT: I just debugged the application ,formz is null at the place I call it(receive function). Why is it null there,but not at any other place?
Upvotes: 0
Views: 2248
Reputation: 1
Check whether you are in debug mode; If so, the active form value returned will be null.
Upvotes: 0
Reputation: 59635
I do not think, it will solve your problem, but have you thought about using the following pattern to do the invoke? I consider it much more readable. Create this extension method.
public static class ControlExtension
{
public static void ThreadSafeInvoke(this Control control, MethodInvoker method)
{
if (control != null)
{
if (control.InvokeRequired)
{
control.Invoke(method);
}
else
{
method.Invoke();
}
}
}
}
And then you can perform thread safe method calls like this.
Form form = new Form();
form.ThreadSafeInvoke(() => form.Text = "ThreadSafeInvoke");
Or multiple calls at once.
form.ThreadSafeInvoke(() =>
{
form.Text = "ThreadSafeInvoke";
form.Visible = true;
form.WindowState = FormWindowState.Maximized;
});
UPDATE
So the problem is clearly Form.ActiveForm
returning null
.
Upvotes: 2
Reputation: 3928
If ActiveForm is returning null then you might not have an active form or it is not of type Form1. You are using "as Form1", so if you have a Form2 which is active then formz will be set to null.
Can you pass formz into the function instead of calling ActiveForm?
Upvotes: 1