2013-04-02 69 views
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; 
} 

这在我看来很丑陋。有没有更好的方法来缩短这段代码?我不知道我怎么可能通过这些单选按钮迭代...

+0

这是什么语言?您需要提供更多详细信息,否则问题将被标记,删除并从记录中删除。 –

+0

我忘了提及。我用C#使用WinForms。 – TheScholar

+0

对不起......从来没有用过C#。 C#是否具有单选按钮组的概念?也许你可以找到基于此的价值?抓住吸管......我知道。 –

回答

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); 
     } 
    } 
} 
+0

小问题是我的按钮不是动态创建的,但它绝对有帮助,我应该从这个示例中找到解决方案。 – TheScholar