运行时在C#中添加控件

时间:2015-04-27 20:10:39

标签: c# windows-forms-designer

我正在创建一个应用程序,我想在动态上从我的主窗体中添加面板上的按钮。如果我在列表中有10个项目,那么将在主窗体的面板上生成许多按钮。但是当我尝试这样做时,它会向我显示Control.Invoke所需的错误。

请有人建议我如何添加控件...... ??

private void CheckOrderListEntry(Workorder workorder)
    {
        int ticketID = workorder.TicketID;
        int index = 0;
        int lastIndex = _workorderList.Count;
        bool isExist = false;

        for (index = 0; index < lastIndex; index++)
        {
            int existingTicektId = _workorderList[index].TicketID;

            if (ticketID == existingTicektId)
            {
                _workorderList[index] = workorder;
                isExist = true;
                break;
            }
        }

        if (!isExist)
        {
            _workorderList.Add(workorder);
        }

        ListEventChangeHandler();
    }

    public void ListEventChangeHandler()
    {
        _orderBtn = new Button[_workorderList.Count];
        int index = 0;
        int lastIndex = _orderBtn.Length;

        for (; index < lastIndex; index++)
        {
            Workorder workorder = _workorderList[index];
            _orderBtn[index] = new Button();
            _orderBtn[index].Name = String.Format("{0}", index);
            _orderBtn[index].Text = String.Format("Order #: {0} Source: {1} Desination: {2}", workorder.TicketID, workorder.PickupAddress, workorder.DropoffAddress);
            _orderBtn[index].BackColor = Color.SteelBlue;
            _orderBtn[index].ForeColor = Color.White;
            _orderBtn[index].Font = new Font("Tahoma", 16, FontStyle.Regular);
            _orderBtn[index].Click += new EventHandler(OrderBtnClick);
        }

        UpdatePanel(_orderBtn);
    }

    public delegate void UpdateAcceptOrderPanel(Button[] btn);
    public void UpdatePanel(Button[] btn)
    {
        try
        {
            if (this.InvokeRequired)
            {
                UpdateAcceptOrderPanel updateMyPanel = new UpdateAcceptOrderPanel(UpdatePanel);
                this.Invoke(updateMyPanel, btn);
            }
            else
            {
                AddButtonOnPanel(btn);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

    }

    public void AddButtonOnPanel(Button[] btn)
    {
        for (int index = 0; index < btn.Length; index++)
        {
            this.acceptOrderPanle.Controls.Add(btn[index]);
        }

    }

1 个答案:

答案 0 :(得分:0)

我对代表不是很好,但这就是我使用UpdatePanel方法的方式......

User
希望这有帮助...

相关问题