如何在Windows窗体应用程序中分组单选按钮(很像ASP。净radiobuttonlist !) ?
所以我可以在选项中选择的每个情况之间切换。
如何在Windows窗体应用程序中分组单选按钮(很像ASP。净radiobuttonlist !) ?
所以我可以在选项中选择的每个情况之间切换。
当前回答
您应该将组的所有单选按钮放在相同的容器中,例如GroupBox或Panel。
其他回答
无面板单选按钮
public class RadioButton2 : RadioButton
{
public string GroupName { get; set; }
}
private void RadioButton2_Clicked(object sender, EventArgs e)
{
RadioButton2 rb = (sender as RadioButton2);
if (!rb.Checked)
{
foreach (var c in Controls)
{
if (c is RadioButton2 && (c as RadioButton2).GroupName == rb.GroupName)
{
(c as RadioButton2).Checked = false;
}
}
rb.Checked = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
//a group
RadioButton2 rb1 = new RadioButton2();
rb1.Text = "radio1";
rb1.AutoSize = true;
rb1.AutoCheck = false;
rb1.Top = 50;
rb1.Left = 50;
rb1.GroupName = "a";
rb1.Click += RadioButton2_Clicked;
Controls.Add(rb1);
RadioButton2 rb2 = new RadioButton2();
rb2.Text = "radio2";
rb2.AutoSize = true;
rb2.AutoCheck = false;
rb2.Top = 50;
rb2.Left = 100;
rb2.GroupName = "a";
rb2.Click += RadioButton2_Clicked;
Controls.Add(rb2);
//b group
RadioButton2 rb3 = new RadioButton2();
rb3.Text = "radio3";
rb3.AutoSize = true;
rb3.AutoCheck = false;
rb3.Top = 80;
rb3.Left = 50;
rb3.GroupName = "b";
rb3.Click += RadioButton2_Clicked;
Controls.Add(rb3);
RadioButton2 rb4 = new RadioButton2();
rb4.Text = "radio4";
rb4.AutoSize = true;
rb4.AutoCheck = false;
rb4.Top = 80;
rb4.Left = 100;
rb4.GroupName = "b";
rb4.Click += RadioButton2_Clicked;
Controls.Add(rb4);
}
如果你不能将它们放到一个容器中,那么你必须编写代码来改变每个RadioButton的checked状态:
private void rbDataSourceFile_CheckedChanged(object sender, EventArgs e)
{
rbDataSourceNet.Checked = !rbDataSourceFile.Checked;
}
private void rbDataSourceNet_CheckedChanged(object sender, EventArgs e)
{
rbDataSourceFile.Checked = !rbDataSourceNet.Checked;
}
看看把你的单选按钮放在一个GroupBox。
将单选按钮放入GroupBox(或其他面板)内
默认情况下,共享容器内的所有单选按钮都在同一个组中。 意思是,如果你选中了其中一个,其他的将不勾选。 如果您想要创建独立的单选按钮组,则必须将它们放置到不同的容器(如Group Box)中,或者通过后面的代码控制它们的Checked状态。