How to create Radio Buttons from a String Array in C#

This following example creates radio button controls and set their text from an array of strings programmatically. The example draws the radio button in vertical direction.

private void Form_load(object sender, EventArgs e)
{
    string[] string_Array = new string[3];
 
    string_Array[0] = "USA";
    string_Array[1] = "India";
    string_Array[2] = "Germany";
 
	DrawRadioButtons(string_Array);
}
 
private void DrawRadioButtons(string[] ArrayOfString)
{
    System.Windows.Forms.RadioButton[] btnRadio = new System.Windows.Forms.RadioButton[string_Array.Length];
 
    for (int i = 0; i < ArrayOfString.Length; ++i)
    {
        btnRadio[i] = new RadioButton();
        btnRadio[i].Text = ArrayOfString[i];
        btnRadio[i].Location = new System.Drawing.Point(10, 30 + i * 20);
        this.Controls.Add(btnRadio[i]);
    }
}

See the output on the windows form:

Create radio buttons from array

You can draw radio buttons horizonatally or vertically using the ‘Location’ property. In the above example we creating and adding radio buttons on the form in vertically direction.

If you want to select specified radio button by default, you can use the ‘Checked’ property. Let’s take an example: Suppose you have a List collection of the ‘city’ class which has ‘Name’ and ‘Value’ properties.

  public class City
    {
        public string CityName { get; set; }
        public Boolean Value { get; set; }
    }

Now construct the list of the city by adding three cities with name and value.

private void Form_load(object sender, EventArgs e)
{
    List<City> Cities = new List<City>();
    // Add cities to the list.
    Cities.Add(new City() { CityName = "USA", Value = false });
    Cities.Add(new City() { CityName = "India", Value = true });
    Cities.Add(new City() { CityName = "Germany", Value = false });
}
 
private void DrawRadioButtons( List<City> Cities)
{
    System.Windows.Forms.RadioButton[] btnRadio = new System.Windows.Forms.RadioButton[Cities.Count];
    for (int i = 0; i < Cities.Count; ++i)
    {
        btnRadio[i] = new RadioButton();
        btnRadio[i].Text = Cities[i].CityName;
        btnRadio[i].Checked = Cities[i].Value;
        btnRadio[i].Location = new System.Drawing.Point(10, 30 + i * 20);
        this.Controls.Add(btnRadio[i]);
    }
}

We are using ‘Name’ property for showing text for radio buttons and ‘Value’ property for making check state of the radio buttons.