【问题标题】:Working with Radio Buttons使用单选按钮
【发布时间】:2013-09-20 18:12:59
【问题描述】:

我有一个程序,它根据选择的单选按钮(用户的选择)以两种不同的方式执行代码。我的问题是无法获取用户选择的内容,这意味着假设基于单选按钮选择以不同方式执行的代码,该代码段不会执行。

这是我所做的:-

这是我确定用户从单选按钮中选择的部分

public Airplane_Simulation()
{
    InitializeComponent();
    if (rbZero.Checked==true) //checks whether it is selected
    {
        section = rbZero.Text; //if true assigns it's text to a variable.
    }
    else if (rbOne.Checked == true)
    {
        section = rbOne.Text;
    }  

    semaphore = new Semaphore();
    buff = new Buffer();
    btnPnlT1 = new ButtonPanelThread(new Point(40, 5), 50, pnlArrival, false, Color.Red, semaphore, buff, btnGo);
    waitingTakeOff = new waitPanels(new Point(490, 5), 50, pnlTakeOff, false, Color.Green, semaphore, buff,section);
    thread1 = new Thread(new ThreadStart(btnPnlT1.start));
    thread3 = new Thread(new ThreadStart(waitingTakeOff.start));
    thread1.Start();
    thread3.Start();
}

这是应该根据用户选择执行的代码

if(section.Equals("0"))  //if the variable match 0 it should this code
{
    for (int k = 0; k < 15; k++)
    {
        panel.Invalidate();
        this.movePlane(xDelta, yDelta);
        Thread.Sleep(delay);
    }
}

else if (section.Equals("1"))   // if variable matches 1 it 
                                // should execute this code
{
    for (int k = 0; k < 40; k++)
    {
        panel.Invalidate();
        this.movePlane(xDelta, yDelta);
        Thread.Sleep(delay);
    }
}

我尝试将值直接分配给变量部分而不从单选按钮中获取,然后它起作用了。所以我确信这与使用单选按钮时的分配有关。

感谢您的宝贵时间。

【问题讨论】:

  • 当您的表单第一次打开时,您只检查选择了哪一个,用户没有机会选择一个,您需要创建一个选择更改事件,顺便说一句else if 可能是两行创建嵌套 if 语句而不是 elseif or else
  • 能显示 RadioButton 事件的代码吗?
  • 我没有为单选按钮创建任何更改事件,所以我会尝试创建它们。再次感谢:)

标签: c# winforms if-statement radio-button panel


【解决方案1】:

当您的表单第一次打开时,您只检查选择了哪个,用户没有机会选择一个,您需要创建一个选择更改事件

顺便说一句,两行上的else if 可能会创建一个嵌套的 if 语句,而不是 else ifelse

您可以这样做的一种方法是,

public Airplane_Simulation()
       {

        InitializeComponent();
        CheckedChanged();
        rbZero.CheckedChanged += (s,e) => { CheckedChanged(); }
        rbOne.CheckedChanged += (s,e) => { CheckedChanged(); }



public void CheckedChanged()
{
    section =  rbZero.Checked ? rbZero.Text : rbOne.Text;
}

否则在设计模式下双击单选按钮。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多