如何从25个ComboBox填充数组?遇System.NullReferenceException求解决
Hey there! Let's figure out why you're hitting that System.NullReferenceException and fix it up step by step.
That exception pops up because at least one of your ComboBoxes has a null value for SelectedValue when you try to call .ToString() on it. This usually happens if a user hasn't selected an option in that ComboBox, or if the control's data source wasn't set up correctly. In rare cases, it could also mean a ComboBox control itself wasn't properly instantiated (like if you misspelled its name in code).
1. Quick Fix: Add Null Checks for Each ComboBox
You can use C#'s null-safe operators to handle null values gracefully without crashing. Replace your existing array initialization with this pattern:
string[] Answers = { cbxIntro.SelectedValue?.ToString() ?? string.Empty, cbxAge.SelectedValue?.ToString() ?? string.Empty, // Repeat this line for all 25 of your ComboBoxes };
- The
?.operator safely calls.ToString()only ifSelectedValueisn't null (otherwise it returns null). - The
??operator replaces that null with an empty string, so you won't trigger the exception.
2. Cleaner Approach: Iterate Over a Collection of ComboBoxes
Writing 25 lines manually is tedious and error-prone. Instead, collect all your ComboBoxes into a list first, then generate the array in one go:
// First, gather all your ComboBoxes (do this in your form's constructor or Load event) var allComboBoxes = new List<ComboBox> { cbxIntro, cbxAge, /* Add the rest of your 23 ComboBoxes here */ }; // Now generate the answers array with automatic null handling string[] Answers = allComboBoxes .Select(combo => combo.SelectedValue?.ToString() ?? string.Empty) .ToArray();
This makes your code shorter and easier to maintain—if you ever add or remove a ComboBox, you just update the list instead of editing 25 separate lines.
3. Optional: Validate User Input First
If you require users to select an option for every ComboBox before submitting, add a validation step to catch missing selections early:
var allComboBoxes = new List<ComboBox> { cbxIntro, cbxAge, /* ... */ }; // Check if any ComboBox has no selection var unselectedCombo = allComboBoxes.FirstOrDefault(combo => combo.SelectedValue == null); if (unselectedCombo != null) { MessageBox.Show($"Please select an option for {unselectedCombo.Name}!"); unselectedCombo.Focus(); // Direct the user to the missing selection return; // Stop further execution until the issue is fixed } // If all are selected, generate the array safely string[] Answers = allComboBoxes.Select(combo => combo.SelectedValue.ToString()).ToArray();
If you still run into issues, check these common pitfalls:
- Are all your ComboBoxes properly bound to a data source? If
DataSourceisn't set,SelectedValuemight stay null even if a user picks an option. - Did you accidentally misspell a ComboBox name? If a control variable is null (because the name doesn't match the design), accessing
SelectedValuewill throw the same exception. - Are you running this code before the form finishes initializing? Wait until the
Form_Loadevent to access control properties, not in the form's constructor.
内容的提问来源于stack exchange,提问作者Will Balderstone

