C#实现选中指定单选按钮时隐藏多个文本框的问题
It sounds like the main issue here is that your visibility logic is tied to a button click event, which only runs when you press the button—not when you select the RadioButton itself. Let's fix that by moving the logic to the RadioButton's CheckedChanged event, which triggers automatically whenever the radio button's selection state changes.
Step 1: Attach the CheckedChanged Event Handler
First, you need to link your RadioButton to an event handler that runs when it's selected. You can do this two ways:
Via Visual Studio Designer
- Select your RadioButton in the designer.
- Open the Properties window (press F4 if it’s hidden).
- Click the lightning bolt icon to view events.
- Double-click the
CheckedChangedevent to auto-generate the handler method.
Or Manually in Code (Form Constructor)
Add this line inside your form's constructor (right after InitializeComponent()):
radioButtonYourTargetName.CheckedChanged += RadioButton_CheckedChanged;
Step 2: Implement the Visibility Logic
Now, write the code inside the event handler to hide your TextBoxes when the RadioButton is checked. Here's a clear example:
private void RadioButton_CheckedChanged(object sender, EventArgs e) { // Cast the sender to RadioButton to check its current state RadioButton selectedRadio = sender as RadioButton; if (selectedRadio != null && selectedRadio.Checked) { // Hide all your target TextBoxes here textBoxLength.Visible = false; textBoxWidth.Visible = false; textBoxHeight.Visible = false; // Add any other TextBoxes you need to hide } else { // Optional: Show the TextBoxes again if another RadioButton is selected textBoxLength.Visible = true; textBoxWidth.Visible = true; textBoxHeight.Visible = true; } }
Why Your Original Code Didn't Work
Your current code lives in buttonBeregn_Click, which only executes when you click that specific button. The RadioButton's selection change doesn't trigger this method automatically. By moving the logic to CheckedChanged, it runs immediately when the user selects or deselects the radio button—no button press required.
Quick Tips
- Double-check that you’re using the exact control names from your designer (typos here will break the code).
- If you have multiple RadioButtons in a group, you can reuse this same event handler for all of them—just add conditions to check which radio button is checked and adjust visibility accordingly.
- Test it out by selecting the RadioButton directly (no need to press your calculate button) to confirm the TextBoxes hide right away.
内容的提问来源于stack exchange,提问作者Undertaker

