You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中动态创建Button并将传入字符串参数作为按钮名称

实现方案

C# 是静态编译语言,无法在运行时动态生成本地变量的名称,你需求中提到的「将传入的name字符串参数作为对应Button的名称」,实际是设置Button实例的Name属性,正确实现代码如下:

private void CreateButton(string name, string text, int x, int y, int sizeX, int sizeY)
{
    Button newBtn = new Button();
    // 将传入的name参数赋值给按钮的Name属性,作为按钮的唯一标识
    newBtn.Name = name;
    newBtn.Location = new System.Drawing.Point(x, y);
    newBtn.Text = text;
    newBtn.Size = new System.Drawing.Size(sizeX, sizeY);
    newBtn.TabIndex = 1;
    newBtn.UseVisualStyleBackColor = true;
    // 事件绑定可后续补充,此处暂不实现
    this.Controls.Add(newBtn);
}

如果后续需要通过名称获取对应按钮,可直接从窗体的Controls集合检索:

// 按传入的name值查找对应按钮
Button targetBtn = this.Controls.Find("你的按钮name值", true).FirstOrDefault() as Button;
if (targetBtn != null)
{
    // 执行按钮相关操作
}

内容的提问来源于stack exchange,提问作者Marco de Boer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 12:36:00