You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

WinForm中Panel动态添加多个单选按钮仅显示一个的问题求助

解决WinForm Panel中动态添加RadioButton仅显示一个的问题

嗨,我一眼就看出问题所在啦——你创建的所有单选按钮都重叠在一起了!因为WinForms控件默认的Location属性是(0, 0),所有按钮都堆在Panel的左上角,自然只能看到最上面那一个。

解决思路

给每个动态创建的RadioButton设置不同的位置坐标,让它们在Panel里有序排列。这里提供两种常见的布局方式供你选择:

1. 纵向排列(从上到下依次排列)

在循环外初始化一个用于控制垂直位置的变量,每次创建按钮时更新这个变量,让按钮依次往下排:

string NewFilePath = "E:\\Tables.txt";
string[] Records = File.ReadAllLines(NewFilePath);

// 初始化垂直起始位置,留一点边距
int yPosition = 10;
// 按钮之间的间距
int spacing = 5;

foreach (string items in Records) {
    RadioButton a = new RadioButton();
    a.Click += new EventHandler(a_Click);
    a.Appearance = Appearance.Button;
    a.Font = new Font("Cambria", 10, FontStyle.Regular);
    a.Width = 75;
    a.Height = 50;
    a.FlatStyle = FlatStyle.Standard;
    a.Cursor = Cursors.Hand;
    a.Name = items;
    a.Text = items.ToString();
    a.TextAlign = ContentAlignment.MiddleCenter;
    a.BackColor = Color.White;
    a.ForeColor = Color.Black;
    
    // 设置按钮位置,横向留10px边距,纵向按顺序排列
    a.Location = new Point(10, yPosition);
    // 更新下一个按钮的垂直位置
    yPosition += a.Height + spacing;
    
    pnlCustomrdb.Controls.Add(a);
}

2. 横向排列(从左到右,超出宽度自动换行)

如果希望按钮横向排列,当一行放不下时自动换到下一行,可以这样写:

string NewFilePath = "E:\\Tables.txt";
string[] Records = File.ReadAllLines(NewFilePath);

int xPosition = 10;
int yPosition = 10;
int spacing = 5;

foreach (string items in Records) {
    RadioButton a = new RadioButton();
    // 其他属性设置和上面一致
    a.Click += new EventHandler(a_Click);
    a.Appearance = Appearance.Button;
    a.Font = new Font("Cambria", 10, FontStyle.Regular);
    a.Width = 75;
    a.Height = 50;
    a.FlatStyle = FlatStyle.Standard;
    a.Cursor = Cursors.Hand;
    a.Name = items;
    a.Text = items.ToString();
    a.TextAlign = ContentAlignment.MiddleCenter;
    a.BackColor = Color.White;
    a.ForeColor = Color.Black;
    
    // 检查当前按钮是否超出Panel宽度,超出则换行
    if (xPosition + a.Width > pnlCustomrdb.ClientSize.Width) {
        xPosition = 10;
        yPosition += a.Height + spacing;
    }
    
    a.Location = new Point(xPosition, yPosition);
    xPosition += a.Width + spacing;
    
    pnlCustomrdb.Controls.Add(a);
}

额外提示

如果不想手动计算位置,也可以给Panel添加一个FlowLayoutPanel控件,把RadioButton添加到FlowLayoutPanel里,它会自动帮你处理布局,省掉手动计算坐标的麻烦哦!

内容的提问来源于stack exchange,提问作者Aasish Grg

火山引擎 最新活动