簡體   English   中英

如何不使用if子句而獲得所選單選按鈕的文本?

[英]How can I get the text of the selected Radio Button without to use the if clause?

我有一個帶有大量單選按鈕(50+)的Windows Forms應用程序。 我有一個用於所有單選按鈕的事件處理程序:

private void RadioButton_CheckedChanged(object sender, EventArgs e)
{
    if(sender == (RadioButton)radioButton1)
    {
         selectedItem = radioButton1.Text;
    }
    else
    {
         selectedItem = radioButton2.Text;
    }
}

對於兩個單選按鈕,效果很好。 如何不使用if子句而獲得所選單選按鈕的文本? 謝謝你,保羅

像這樣; 但您還需要檢查是否已選中,因為同時取消選中單選按鈕時也會觸發事件, 請參見

private void RadioButton_CheckedChanged(object sender, EventArgs e)
{
    //cast and store for future use.
    var senderRadioButton = (RadioButton)sender; 

    //check if sender is checked
    if (senderRadioButton.Checked)
        selectedItem = senderRadioButton.Text;

    //else
}

確保將所有更改的事件連接到此處理程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM