If this is a web application I would recommend you take a look at the
RadioButtonList Class. You access the radio button you want to select by through the RadioButton's Items property.
For example, if you had the following RadioButtonList declared in your ASPX code:
-
<asp:RadioButtonList ID="titles" runat="server">
-
<asp:ListItem id="mr" Text="Mr" Value="Mr"></asp:ListItem>
-
<asp:ListItem id="miss" Text="Miss" Value="Miss"></asp:ListItem>
-
<asp:ListItem id="mrs" Text="Mrs" Value="Mrs"></asp:ListItem>
-
</asp:RadioButtonList>
You would select "Mrs" using C# like this:
-
titles.Items[2].Selected = true;
If you are developing a desktop application and you want the user to be able to select one value from a group of
RadioButtons, then you need group the RadioButtons together in a GroupBox or Panel. Once they are grouped you use the Checked property to set the RadioButton that you want selected.
For example:
-
-
private GroupBox radioGroup;
-
private RadioButton mrRadio;
-
private RadioButton missRadio;
-
private RadioButton mrsRadio;
-
-
//The following method initializes the RadioButtons in a the GroupBox:
-
public void InitializeRadioButtons()
-
{
-
this.radioGroup = new System.Windows.Forms.GroupBox();
-
-
this.mrRadio = new System.Windows.Forms.RadioButton();
-
this.missRadio = new System.Windows.Forms.RadioButton();
-
this.mrsRadio = new System.Windows.Forms.RadioButton();
-
-
this.radioGroup.Controls.Add(this.mrRadio);
-
this.radioGroup.Controls.Add(this.missRadio);
-
this.radioGroup.Controls.Add(this.mrsRadio);
-
-
-
this.radioGroup.Location = new System.Drawing.Point(80, 75);
-
this.radioGroup.Height = 150;
-
this.radioGroup.Text = "Titles";
-
-
this.mrRadio.Text = "Mr";
-
this.mrRadio.Location = New Point(5, 15);
-
-
this.missRadio.Text = "Miss";
-
this.missRadio.Location = New Point(5, 35);
-
-
this.mrsRadio.Text = "Mrs";
-
this.mrsRadio.Location = New Point(5, 55);
-
-
//Selecting "Mrs"
-
this.mrsRadio.Checked = true;
-
-
this.ClientSize = new System.Drawing.Size(292, 266);
-
this.Controls.Add(this.radioGroup);
-
}