-2

I have problem in adding button in panel, I already read how to use delegate and I write it in my code, But after that only this exception is suppressed But no Button Added to my Panel. Here is My Code

public delegate void AddControlToPanelDlgt(Panel panel, Control ctrl);  
    private void AddControlToPanel(Panel panel, Control ctrl)
    {
        if (panel.InvokeRequired)
        {
            panel.Invoke(new AddControlToPanelDlgt(AddControlToPanel), panel, ctrl);
            return;
        }
        if (ctrl.InvokeRequired)
        {
            ctrl.Invoke(new AddControlToPanelDlgt(AddControlToPanel), panel, ctrl);
            return;
        }
        panel.Controls.Add(ctrl); //<-- here is where the exception is raised
    }
Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58

2 Answers2

0

I think you should remove if (ctrl.InvokeRequired) it is not needed,

private void AddControlToPanel(Panel panel, Control ctrl)
{
    if (panel.InvokeRequired)
    {
       panel.Invoke(new AddControlToPanelDlgt(AddControlToPanel), new object[] { panel, ctrl });          
    }
    else
        panel.Controls.Add(ctrl); //<-- here is where the exception is raised
}

As per the comments by Hans Passant it is absolutely right that you have added the Control successfully but it could be hidden underneath another control or have the wrong Location that's why it is not displayed.

Community
  • 1
  • 1
Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58
0

Please make sure panel and ctrl is not null first

private void AddControlToPanel(Panel panel, Control ctrl)
    {
        if (panel.InvokeRequired)
        {
            panel.Invoke(new Action<Panel, Control>(AddControlToPanel), panel, ctrl);
            return;
        }
        else
        {
            panel.Controls.Add(ctrl);
        }
    }
RyanWang
  • 178
  • 9