그룹의 어떤 라디오 버튼이 점검됩니까?
WinForms 사용; 그룹에 대해 확인 된 RadioButton을 찾는 더 좋은 방법이 있습니까? 아래 코드가 필요하지 않은 것 같습니다. 다른 RadioButton을 확인하면 선택 해제해야 할 항목을 알 수 있으므로 어느 것이 선택되어 있는지 알아야합니다. 많은 if 문 (또는 스위치)을 수행하지 않고 해당 정보를 가져 오는 방법은 무엇입니까?
RadioButton rb = null;
if (m_RadioButton1.Checked == true)
{
rb = m_RadioButton1;
}
else if (m_RadioButton2.Checked == true)
{
rb = m_RadioButton2;
}
else if (m_RadioButton3.Checked == true)
{
rb = m_RadioButton3;
}
LINQ를 사용할 수 있습니다 :
var checkedButton = container.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked);
이를 위해서는 모든 단일 선택 단추가 동일한 컨테이너 (예 : 패널 또는 양식)에 직접 있어야하며 컨테이너에 하나의 그룹 만 있어야합니다. 그렇지 않은 경우 List<RadioButton>
생성자에서 각 그룹에 대해을 작성한 다음을 쓸 수 list.FirstOrDefault(r => r.Checked)
있습니다.
모든 버튼 의 CheckedEvents 를 하나의 핸들러에 연결할 수 있습니다 . 거기에서 올바른 확인란을 쉽게 얻을 수 있습니다.
// Wire all events into this.
private void AllCheckBoxes_CheckedChanged(Object sender, EventArgs e) {
// Check of the raiser of the event is a checked Checkbox.
// Of course we also need to to cast it first.
if (((RadioButton)sender).Checked) {
// This is the correct control.
RadioButton rb = (RadioButton)sender;
}
}
LINQ가없는 경우 :
RadioButton GetCheckedRadio(Control container)
{
foreach (var control in container.Controls)
{
RadioButton radio = control as RadioButton;
if (radio != null && radio.Checked)
{
return radio;
}
}
return null;
}
OP는 확인 된 RadioButton BY GROUP을 가져 오려고했습니다. @SLaks의 대답은 훌륭하지만 실제로 OP의 주요 질문에 대답하지는 않습니다. @SLaks의 답변을 향상 시키려면 LINQ를 한 단계 더 나아가십시오.
다음은 내 작업 코드의 예입니다. 일반적인 WPF에 따라 내 RadioButton은 Grid
다른 유형의 컨트롤과 함께 "myGrid"라는 이름으로 포함되어 있습니다. 그리드에 두 개의 다른 RadioButton 그룹이 있습니다.
특정 그룹에서 확인 된 RadioButton을 가져 오려면 :
List<RadioButton> radioButtons = myGrid.Children.OfType<RadioButton>().ToList();
RadioButton rbTarget = radioButtons
.Where(r => r.GroupName == "GroupName" && r.IsChecked)
.Single();
코드에서 RadioButton을 확인할 가능성이없는 SingleOrDefault()
경우 다음을 사용하십시오. (세 상태 버튼을 사용하지 않는 경우 항상 하나의 버튼을 "IsChecked"를 기본 선택으로 설정합니다.)
You can use the CheckedChanged event for all your RadioButtons. Sender
will be the unchecked and checked RadioButtons.
You can use an Extension method to iterate the RadioButton's Parent.Controls collection. This allows you to query other RadioButtons in the same scope. Using two extension methods, you can use the first determine whether any RadioButtons in the group are selected, then use the second to get the selection. The RadioButton Tag field can be used to hold an Enum to identify each RadioButton in the group:
public static int GetRadioSelection(this RadioButton rb, int Default = -1) {
foreach(Control c in rb.Parent.Controls) {
RadioButton r = c as RadioButton;
if(r != null && r.Checked) return Int32.Parse((string)r.Tag);
}
return Default;
}
public static bool IsRadioSelected(this RadioButton rb) {
foreach(Control c in rb.Parent.Controls) {
RadioButton r = c as RadioButton;
if(r != null && r.Checked) return true;
}
return false;
}
Here's a typical use pattern:
if(!MyRadioButton.IsRadioSelected()) {
MessageBox.Show("No radio selected.");
return;
}
int selection = MyRadioButton.GetRadioSelection;
In addition to the CheckedChangedEvent wiring one could use the Controls "Tag" property to distinguish between the radio buttons... an (spaghetti code) alternative would be the "TabIndex" property ;P
Sometimes in situations like this I miss my youth, when Access was my poison of choice, and I could give each radio button in a group its own value.
My hack in C# is to use the tag to set the value, and when I make a selection from the group, I read the value of the tag of the selected radiobutton. In this example, directionGroup is the group in which I have four five radio buttons with "None" and "NE", "SE", "NW" and "SW" as the tags on the other four radiobuttons.
I proactively used a button to capture the value of the checked button, because because assigning one event handler to all of the buttons' CHeckCHanged event causes EACH button to fire, because changing one changes them all. So the value of sender is always the first RadioButton in the group. Instead, I use this method when I need to find out which one is selected, with the values I want to retrieve in the Tag property of each RadioButton.
private void ShowSelectedRadioButton()
{
List<RadioButton> buttons = new List<RadioButton>();
string selectedTag = "No selection";
foreach (Control c in directionGroup.Controls)
{
if (c.GetType() == typeof(RadioButton))
{
buttons.Add((RadioButton)c);
}
}
var selectedRb = (from rb in buttons where rb.Checked == true select rb).FirstOrDefault();
if (selectedRb!=null)
{
selectedTag = selectedRb.Tag.ToString();
}
FormattableString result = $"Selected Radio button tag ={selectedTag}";
MessageBox.Show(result.ToString());
}
FYI, I have tested and used this in my work.
Joey
if you want to save the selection to file or any else and call it later, here what I do
string[] lines = new string[1];
lines[0] = groupBoxTes.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked).Text;
File.WriteAllLines("Config.ini", lines);
then call it with
string[] ini = File.ReadAllLines("Config.ini");
groupBoxTes.Controls.OfType<RadioButton>()
.FirstOrDefault(r => (r.Text == ini[0])).Checked = true;
If you want to get the index of the selected radio button inside a control you can use this method:
public static int getCheckedRadioButton(Control c)
{
int i;
try
{
Control.ControlCollection cc = c.Controls;
for (i = 0; i < cc.Count; i++)
{
RadioButton rb = cc[i] as RadioButton;
if (rb.Checked)
{
return i;
}
}
}
catch
{
i = -1;
}
return i;
}
Example use:
int index = getCheckedRadioButton(panel1);
The code isn't that well tested, but it seems the index order is from left to right and from top to bottom, as when reading a text. If no radio button is found, the method returns -1.
Update: It turned out my first attempt didn't work if there's no radio button inside the control. I added a try and catch block to fix that, and the method now seems to work.
The GroupBox has a Validated event for this purpose, if you are using WinForms.
private void grpBox_Validated(object sender, EventArgs e)
{
GroupBox g = sender as GroupBox;
var a = from RadioButton r in g.Controls
where r.Checked == true select r.Name;
strChecked = a.First();
}
For developers using VB.NET
Private Function GetCheckedRadio(container) As RadioButton
For Each control In container.Children
Dim radio As RadioButton = TryCast(control, RadioButton)
If radio IsNot Nothing AndAlso radio.IsChecked Then
Return radio
End If
Next
Return Nothing
End Function
참고URL : https://stackoverflow.com/questions/1797907/which-radio-button-in-the-group-is-checked
'Programing' 카테고리의 다른 글
선택 2 드롭 다운이지만 사용자가 새 값을 허용 하시겠습니까? (0) | 2020.07.21 |
---|---|
MAC 주소의 정규식은 무엇입니까? (0) | 2020.07.21 |
$ _REQUEST []를 사용하는 데 무엇이 문제입니까? (0) | 2020.07.21 |
Playground에서 비동기 콜백을 실행하는 방법 (0) | 2020.07.21 |
'for'루프를 사용하여 C ++ 벡터를 반복 (0) | 2020.07.21 |