[英]Prevent radiobutton click
我有一個勝利表格,上面有幾個單選按鈕和標簽以及我在運行時生成的其他控件。 當我選中一個單選按鈕時,這不是我想要的,除了我選中的那個以外,所有單選按鈕都應取消選中。 這適用於每個單選按鈕。 簡而言之,我希望一次檢查一個單選按鈕。
private RadioButton GenerateRadioButton(string id)
{
RadioButton _radioButton = new RadioButton();
_radioButton.Location = new Point(32, 20);
_radioButton.Margin = new Padding(4, 4, 4, 4);
_radioButton.Size = new Size(130, 36);
_radioButton.Name = id;
_radioButton.AutoSize = true;
_radioButton.Font = new Font("Arial", 16, FontStyle.Bold);
_radioButton.CheckedChanged += new System.EventHandler(RadioButton_CheckedChanged);
return _radioButton;
}
private void RadioButton_CheckedChanged(object sender, EventArgs e)
{
HandleRadioButtinClick(((RadioButton)sender).Name);
((RadioButton)sender).Checked = true;
}
private void HandleRadioButtinClick(string ctrlId)
{
FrmSpace objFrmSpace = new FrmSpace();
foreach (Control ctrl in pictureBox1.Controls)
{
if (ctrl is Panel)
{
foreach (Control ctl in ctrl.Controls)
{
if (ctl is RadioButton && ctl.Name != ctrlId)
((RadioButton)ctl).Checked = false;
}
}
}
}
這是上面的代碼。 這段代碼的問題是,當我檢查單選按鈕時,如果還有其他任何單選按鈕被選中,而我嘗試取消選中它,則也會觸發其checkedchanged事件,這將導致所有單選按鈕再次被取消選中。 我希望我清楚我想傳達的內容。
請提供一些解決方案。
謝謝
您是否嘗試過對所有單選按鈕使用組框 ? 這是您要的默認功能。
編輯:澄清您的問題
// some function
GroupBox g = createGBox();
this.Controls.Add(g);
g.Controls.Add(radioButton1);
g.Controls.Add(radioButton2);
}
public GroupBox createGBox()
{
GroupBox gBox = new GroupBox();
gBox.Location = new System.Drawing.Point(72, 105);
gBox.Name = "BOX";
gBox.Size = new System.Drawing.Size(200, 100);
gBox.Text = "This is a group box";
return gBox;
}
將所有radiobuttons
放入同一GroupBox
控件中,您也可以在運行時創建該控件。 在這種情況下,預期行為應由控件本身處理,而無需編碼。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.