0

在 C# WinForms 我有几个单选按钮,在我的代码中它看起来像这样:

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;
}

在我看来,这很丑陋。有没有更好的方法来缩短此代码?我不知道如何遍历那些单选按钮...

4

1 回答 1

2

您可以使用 case 语句,但我认为这不是您想要的。

看这个。我将单选按钮创建为动态的。

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);
        }
    }
}
于 2013-04-02T23:01:32.103 回答