This will be an easy one for you musicians out there, but it is something that is holding me back in my song writing hobby.
Ok, i've put a song together, chords are mainly C, Em, F, G with Dm used sparingly, starts on C and all the evidence points it to being in the key of C major. Correct?

The solo/ melody I was playing to compliment the chords I just came up with - it started on B and ambled around the notes D & C, finishing with notes A, G & F# - sounded OK to me but then I thought hmm F#, this solo is in the key of G, even I know the key of C has no sharps!

So I redid it in C, same pattern as before, sounded best starting on E then G,F etc finishing with D,C,B.
Question is what are the rules? Are there any rules? If the song is in key of C, must the solo be in C also ( I know that Am is a complimentary key and this would work, but the solo in G which I was doing is it a no-no?)
Maybe if I recorded the chords and did the solo over it would highlight what worked, but could someone tell me the theory?
Appreciate any advice.