Reputation: 1
I'm trying to add an ListViewItem to a listView on the main form (Form1), from another class(Comm).
Form1:
public ListViewItem lvi_tmp;
private void Form1_Load(object sender, EventArgs e)
{
comm = new Comm(this);
}
public void add_to_reg(ListViewItem tmp)
{
lvi_tmp = tmp;
this.Invoke(new EventHandler(add_to_reg_event));
}
public void add_to_reg_event(Object sender, EventArgs e)
{
lst_reg.Items.Add(lvi_tmp);
lst_reg.Refresh();
this.Refresh();
}
Comm:
public Form1 mainFrm { get; set; }
public Comm (Form1 _form1)
{
mainFrm = _form1;
}
private void Add_item()
{
lvi = new ListViewItem("itemTest");
lvi.SubItems.Add("subitemTest");
lvi.Tag = 1;
mainFrm.add_to_reg(lvi);
}
This code throwing the next Exception:
"Invoke or BeginInvoke cannot be called on a control until the window handle has been created."
Any ideas?
Upvotes: 0
Views: 38
Reputation: 109567
You can check InvokeRequired
before callling BeginInvoke()
. Perhaps this will work for you:
public void add_to_reg(ListViewItem tmp)
{
lvi_tmp = tmp;
if (this.InvokeRequired))
this.Invoke(new EventHandler(add_to_reg_event));
else
add_to_reg_event(null, null);
}
Although I'd split up add_to_reg_event() and use a lambda to avoid that temporary variable:
public void add_to_reg(ListViewItem tmp)
{
if (this.InvokeRequired))
this.Invoke(new Action(() => add_to_reg_impl(tmp)));
else
add_to_reg_impl(tmp);
}
private void add_to_reg_impl(ListViewItem item)
{
lst_reg.Items.Add(item);
lst_reg.Refresh();
this.Refresh();
}
Upvotes: 1