WinForm列表框中存储与访问武器配置值的技术问题
Hey there! Let's fix this issue step by step. The error you're seeing happens because newBeamWeapon is a local variable inside the addBeamWeaponButton_Click method — it only exists within that method's scope, so you can't access it from the selectedBeamWeapons_SelectedIndexChanged event handler.
Luckily, you're already on the right track by storing the full beamWeaponClass object in your listBox2 ( addedBeamWeaponsList ). Here's how to properly retrieve and use that stored data when selecting items:
1. Fix the SelectedIndexChanged Event Handler
Replace your commented-out code in selectedBeamWeapons_SelectedIndexChanged with this:
private void selectedBeamWeapons_SelectedIndexChanged(object sender, EventArgs e) { // First, make sure an item is actually selected if (selectedBeamWeapons.SelectedItem != null) { // Cast the selected item back to your beamWeaponClass type beamWeaponClass selectedWeapon = selectedBeamWeapons.SelectedItem as beamWeaponClass; // Double-check the cast succeeded (in case something unexpected is in the list) if (selectedWeapon != null) { // Sync the UI controls with the stored values beamBonus.Text = selectedWeapon.beamBonusValue; beamCost.Text = selectedWeapon.beamCostValue; beamRange.Text = selectedWeapon.beamRangeValue; beamRecycle.Text = selectedWeapon.beamRecycleValue; // For Beam Arcs, reverse your calculateArcs() logic here // Example: Parse selectedWeapon.beamArcsValue and set your arc input controls to match } } }
2. Confirm Your Add Logic is Working
Your current addBeamWeaponButton_Click method is correctly creating and adding the full beamWeaponClass object to the list — that part is solid! The key detail here is that your listBox2 stores the entire object (not just a display string), so casting the selected item back to beamWeaponClass lets you access all stored configuration values.
3. Optional: Clean Up Naming (Best Practice)
To make your code more readable and maintainable, follow C# naming conventions:
- Rename
beamWeaponClasstoBeamWeapon(PascalCase for class names) - Rename properties like
beamBonusValuetoBeamBonusValue(PascalCase for public properties)
4. Add Remove Functionality (Bonus)
Since you have an empty removeBeamWeaponButton_Click method, here's how to implement that:
private void removeBeamWeaponButton_Click(object sender, EventArgs e) { if (selectedBeamWeapons.SelectedItem != null) { selectedBeamWeapons.Items.Remove(selectedBeamWeapons.SelectedItem); // Optional: Clear UI controls after removal beamBonus.Text = ""; beamCost.Text = ""; beamRange.Text = ""; beamRecycle.Text = ""; } }
内容的提问来源于stack exchange,提问作者Trido

