简体   繁体   中英

Add many radio buttons to groupbox C#

I have values in textbox if x I want to show specific number of radio buttons, if y show other specific number of radio buttons so how to add specific number of radio buttons and control its position and size by code, thanks

You can try implementing good old for loop. If you want to create radiobuttons being stacked vertically :

  //TODO: provide the desired value here
  int numberOfRadioButtons = 7;

  //TODO: Put desired values here
  int left = 15;
  int top = 25;
  int height = 50;

  for (int i = 0; i < numberOfRadioButtons; ++i) {
    RadioButton button = new RadioButton() {
      Parent = myGroupBox,
      Location = new Point(left, top + height * i),
      Text = $"RadioButton # {i}",

      // If you insist on setting size manually, uncomment the lines below
      //AutoSize = false,
      //Size = new Size(200, height),
    };

    // button is created; you can use it, say, to assign event handler:
    //button.Click += MyRadioButtonClick;
  }

Edit: You can use Linq to get checked RadioButton :

  using System.Linq;

  ...

  // Either checked rudio button or null if none of radio button is checked
  RadioButton chosen = myGroupBox
    .Controls
    .OfType<RadioButton>()
    .FirstOrDefault(button => button.Checked); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM