[英]c#: How to add radio buttons dynamically in two rows with a fixed window size
I try to add radio buttons dynamically to a Windows Forms application in two rows (there is always an even amount of radio buttons in my case).我尝试在两行中动态地将单选按钮添加到 Windows Forms 应用程序中(在我的情况下,单选按钮的数量总是相等的)。 I found this question , which helps me to understand how to generally add radio buttons.我发现了这个问题,这有助于我了解如何通常添加单选按钮。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test {
public partial class Form1 : Form {
FlowLayoutPanel pnl = new FlowLayoutPanel();
public Form1() {
InitializeComponent();
}
void radioButtonHandler(object sender, EventArgs e)
{
MessageBox.Show("Radio Button", "Click");
}
private void Form1_Load(object sender, EventArgs e) {
pnl.Dock = DockStyle.Fill;
for (int i = 0; i < 16; i++)
{
pnl.Controls.Add(new RadioButton() { Text = "" + i });
pnl.Controls[i].Click += new EventHandler(this.radioButtonHandler);
}
this.Controls.Add(pnl);
}
}
}
The problem is, the mentioned question doesn't cover the following questions:问题是,提到的问题不包括以下问题:
FlowLayoutPanel flp = new FlowLayoutPanel();
flp.Size = new Size(950, 100);
flp.BorderStyle = BorderStyle.FixedSingle;
flp.AutoScroll = true;
for (int i = 0; i < 20; i++)
{
RadioButton rb = new RadioButton();
rb.Text = i.ToString();
rb.AutoSize = false;
rb.Size = new Size(100, 25);
flp.Controls.Add(rb);
}
this.Controls.Add(flp);
FlowLayoutPanel panel = new FlowLayoutPanel();
panel.AutoScroll = true;
panel.WrapContents= true;
for (int i = 0; i < 16; i++)
{
panel .Controls.Add(new RadioButton()
{
Text = "" + i,
Anchor = AnchorStyles.Top | AnchorStyles.Bottom
| AnchorStyles.Left | AnchorStyles.Right,
AutoSize = true,
Margin = //your styles,
});
panel .Controls[i].Click += new EventHandler(this.radioButtonHandler);
}
setting AnchorStyles help you to keep your controls aligned and by proerties like padding or size you can define size of you elements if all radiobuttons ahave same width you can use size attribute.if they dont have a same size its better to use AnchorStyles.设置 AnchorStyles 可帮助您保持控件对齐,并且通过填充或大小等属性,您可以定义元素的大小,如果所有单选按钮具有相同的宽度,则可以使用 size 属性。如果它们的大小不同,则最好使用 AnchorStyles。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.