Reputation: 2653
In C# WinForms I have several radio buttons, and in my code it looks like this:
public void Adjust_id()
{
if (radio_button_0.Checked)
(database.Record).active_id = 0;
else if (radio_button_1.Checked)
(database.Record).active_id = 1;
else if (radio_button_2.Checked)
(database.Record).active_id = 2;
else if (radio_button_3.Checked)
(database.Record).active_id = 3;
else if (radio_button_4.Checked)
(database.Record).active_id = 4;
else if (radio_button_5.Checked)
(database.Record).active_id = 5;
else if (radio_button_6.Checked)
(database.Record).active_id = 6;
else if (radio_button_7.Checked)
(database.Record).active_id = 7;
else if (radio_button_8.Checked)
(database.Record).active_id = 8;
else if (radio_button_9.Checked)
(database.Record).active_id = 9;
else if (radio_button_A.Checked)
(database.Record).active_id = 10;
else if (radio_button_B.Checked)
(database.Record).active_id = 11;
else if (radio_button_C.Checked)
(database.Record).active_id = 12;
else if (radio_button_D.Checked)
(database.Record).active_id = 13;
else if (radio_button_E.Checked)
(database.Record).active_id = 14;
else if (radio_button_F.Checked)
(database.Record).active_id = 15;
}
It's quite ugly in my opinion. Is there a better approach to shorten this code? I don't know how I could iterate through those radio buttons...
Upvotes: 0
Views: 82
Reputation: 712
You could use a case statement, but I don't think that is what you want.
Look at this. I created the Radio Buttons to be Dynamic.
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
Dictionary<int, RadioButton> RadioButtons = new Dictionary<int,RadioButton>();
public Form1()
{
InitializeComponent();
for (int i = 0; i < 10; i++)
{
int j = i * 30;
CreateRadioButton(i, j);
}
CheckRadioButton(2);
}
public void CheckRadioButton(int active_id)
{
RadioButton singRB = RadioButtons[active_id];
singRB.Checked = true;
}
public void CreateRadioButton(int name, int topAdd)
{
RadioButton RB = new RadioButton();
RB.Left = 20;
RB.Top = 30 + topAdd;
RB.Width = 300;
RB.Height = 30;
RB.Text = String.Format("I am a Dynamic RadioButton {0}", name);
RB.Name = String.Format("RadioButton{0}", name);
RadioButtons.Add(name, RB);
Controls.Add(RB);
}
}
}
Upvotes: 2