Windows assigns numbers to ports as the devices get connected.
If you boot computer with the devices connected, the devices can get assigned port numbers in any random order, and you have no control over the port number assignments and Sonar can only guess what device goes to what track input. Some programs (like Brainspawn Forte) have an option to let you just fix the port mapping manually, (regardless of how Windows assigned port numbers), but Sonar lacks this feature.
I solved the problem in Sonar by this method:
I always boot computer with
no midi devices connected (including sound card because it often has a midi driver). Then I plug in the midi devices
in SAME order,
to same ports. (Pausing to make sure a device is recognized before plugging in next device). I use 4 USB midi controllers connected to a USB hub, and I plug in the hub first (
making sure nothing is connected to hub), then connect midi devices to the hub (
same port, same order). This method works every time.
One you determined the order and then fixed up the track midi inputs (for the last time

) in Sonar,
then from then on, if you forgot to disconnect everything before boot up (and the Sonar Midi inputs are messed up),
DO NOT TRY TO FIX THE MIDI INPUTS IN SONAR (you are just chasing your tail). Just make sure you disconnect everything reboot and do correct orderly boot up and connections.
By trial and error I found the "connection order" that nicely puts the topmost keyboard at beginning of the picklist in Sonar. (Because I found it annoying if the list was not in "top to bottom" order).