Thursday, May 03, 2007

Alpha Strike

Colored in form, made the Cancel button work, and you can now add squads to your new airfleet for your big attack.

Soon I'll add a button called Alpha Strike that'll put all the squadrons into the attack airfleet list. Hey, that might even be a better name than Carrier Wave, too. Anyway, you can hold Ctrl or Shift to do multiple selections. Good old MultiExtended in the Listbox property does it automatically.




A simple click to move the squads to the right...



A small subtlety: see the below error I got when I first tried to add items to the right listbox and then remove them from the left listbox(listSquads). The error repeated three times in my errorlog file.

Thursday, May 03, 2007      9:34 PM
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Windows.Forms.ListBox.ItemArray.GetItem(Int32 virtualIndex, Int32 stateMask)
at System.Windows.Forms.ListBox.SelectedObjectCollection.get_Item(Int32 index)
at Carrier_Wave.frmCreateAirFleet.AddToAirFleet_Click(Object sender, EventArgs e)


Here was the Visual Basic.net code I had (shush, you C# fanatics):

For q = 0 to listSquads.SelectedItems.Count - 1
listAdded.Items.Add(listSquads.SelectedItems(q).ToString)
Next

'remove from
For q = 0 to listSquads.SelectedItems.Count - 1
listSquads.Items.Remove(listSquads.SelectedItems(q).ToString)
Next


I told it the last index (blah.Count-1) and then did a simple for...loop from 0 to the last index. Can you see the problem?

Scroll down a bit and you can see the fix was easy.

.
.
.
.
.
.
.
.
.
.

The removal of items from listSquads meant the last index was getting smaller and smaller. But the for loop kept going to the old, now too big, last index. So I did:

For q = listSquads.SelectedItems.Count - 1 To 0 Step -1
listAdded.Items.Add(listSquads.SelectedItems(q).ToString)
Next

'remove from
For q = listSquads.SelectedItems.Count - 1 To 0 Step -1
listSquads.Items.Remove(listSquads.SelectedItems(q).ToString)
Next


The last index causes the error unless you get rid of them first. Now we don't care if the number of items decreasing causes the last index to change. Basically, the bottom of the list is getting chopped off, but if we get the items at the bottom before that happens, then it doesn't matter.

1 comment:

russellmz said...

first! haha, i always wanted to do that.