You want to use recursion. Your base test is to check if you have a complete and valid Soduku grid. If so stop returning true. Next check to see if anything in the grid causes the puzzle to not be a valid soduku grid. If you find a problem return false. Next set up a loop. Randomly choose an available number for the next square. Then call your function. If it returns true you return true. If false
if it returns false undo the number. If you havent tried all available numbers try again with another. Otherwise return false. There are soduku generation resources online but not too many. Think I found a pdf something like puzzles from easy to evil or something like that. I would look for that if you can find it.
A really clever approach is to have a single, pre-generated sudoku, shuffle each row, then shuffle each column, then shuffle every 3x3 box
And then mask each number with a shuffled different number (replace all 5s with 9s, ...)
Any its as if you just generated a new one, but its much faster
Doing those swaps, however, does have rules, and I think the computation may get out of hand
I don't have very much experience with sudoku generation, but I know its one of those gray areas in Computer Science, it has to do with the famous P vs. NP problem.