From an old printer's axiom. Back in the early days of printing presses, each line of text had to be set up one letter at a time. Since the letters in the press were reversed (so they'd print forward), the printmaker (or typographer) needed to be careful not to confuse one letter for the other.
Reminding someone to "watch his p's and q's" means to pay attention to the details.
On the stand, Bill was always careful to watch his p's and q's when dealing with the lawyers.