winform中动态生成控件

最近做winform程序,算是第一次做winform项目吧,记录一下。

本文介绍了如何在一个winform程序中动态创建控件,以下的代码片段演示了在一个pannel容器中动态生成button的功能。详细代码见Github

代码片段

private void GenerateButton()
{
    panelButton.Controls.Clear();
    var btns = GetButtonList(fakeTotal);
    // 居中算法,计算左,上内边距
    int paddingLeft = (panelButton.Width % (btnWidth + btnGap) + btnGap) / 2;
    int paddingTop = (panelButton.Height % (btnHeight + btnGap) + btnGap) / 2;

    total = btns.Count();
    totalPage = (int)Math.Ceiling((decimal)total / pageSize);
    var beShowButton = btns.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
    int x = 0;
    int y = 0;
    foreach (var item in beShowButton)
    {
        Button btn = new Button();
        btn.Width = btnWidth;
        btn.Height = btnHeight;
        btn.Text = item.Name;
        btn.Font = new Font("宋体", 14);
        btn.Name = $"btn_{item.Id}";
        btn.Left = x * (btn.Width + btnGap) + paddingLeft;
        btn.Top = y * (btn.Height + btnGap) + paddingTop;
        btn.Tag = item;

        // 换行
        if (panelButton.Width - btn.Left <= btn.Width)
        {
            x = 0;
            y++;
            btn.Left = x * (btn.Width + btnGap) + paddingLeft;
            btn.Top = y * (btn.Height + btnGap) + paddingTop;

            if (panelButton.Height - btn.Top <= btn.Height)
            {
                throw new WarningException("按钮设置超出容器范围,部分按钮不可见");
            }
        }
        btn.Click += Btn_Click;
        panelButton.Controls.Add(btn);
        x++;
    }
    watch.Stop();
    label1.Text = $"{watch.ElapsedMilliseconds} ms";
}

private void Btn_Click(object sender, EventArgs e)
{
    Button button = (Button)sender;
    // do something
}

你可能感兴趣的:(Winform)