【问题标题】:Add buttons Dynamically at Runtime在运行时动态添加按钮
【发布时间】:2012-08-09 09:10:20
【问题描述】:

我想在 c sharp windows 窗体上动态添加按钮。按钮的数量应该等于数据表中可用的记录数量,并且我想显示单击其按钮的记录。有人可以帮帮我吗?

【问题讨论】:

  • 到目前为止你尝试了什么?
  • for 循环到可用记录的计数 --> Button myButton = new Button(); --> myPanel.Controls.Add(myButton); ???

标签: c# winforms button dynamic


【解决方案1】:

在您的情况下,您需要创建将在 UI 上表示您的项目记录的用户控件,创建在此用户控件中支持您的项目和公共事件的构造函数,并像这样添加到您的容器中。

myPanel.Controls.Add(new ItemRecordUserControl(item));

您可能需要使用一些特定容器而不是常规面板,例如System.Windows.Forms.FlowLayoutPanel .

用户控件如下所示:

public partial class ItemRecorUserControl : UserControl
{
    public event EventHandler<EventArgs> ActionButtonClicked;

    public void OnActionButtonClicked(object sender, EventArgs e)
    {
        if (this.ActionButtonClicked != null)
            this.ActionButtonClicked(sender, e);
    }

    public ItemRecorUserControl()
    {
        InitializeComponent();
    }

    public ItemRecorUserControl(ItemRecord item) : this()
    {
        // fill item data here to controls
    }

    private void btnAction_Click(object sender, EventArgs e)
    {
        this.OnActionButtonClicked(sender, e);
    }
}

【讨论】:

    【解决方案2】:

    你可以像这样添加按钮:

    for (int i = 0; i < YourDataTableItemsCount; i++)
       {
           Button b = new Button();
           b.Left = //Calculate Left
           b.Top = //Calculate Top
           b.Parent = this; 
           //Or
           this.Controls.Add(b);
       }
    

    【讨论】:

      猜你喜欢
      • 2016-04-30
      • 1970-01-01
      • 2019-03-12
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      相关资源
      最近更新 更多