I came across a similar question in the past. Just copied it and will paste it. It's a lot to read and gives (hopefully) some explanation to your question. Short answer: it's a matter of the case you use in the German language. There are four of them.
That's a lot of grammar. I will write some examples. But first: "Fall" = grammatical case.
The accusative case (first case) indicates the direct object of a verb: The clerk remembered us. Sentences without prepositions.
The genitive case (second case), which roughly corresponds to English's possessive case: John's book was on the table.
The dative case (third case) indicates the indirect object of a verb: The clerk gave us a discount.
The nominative case (the fourth case) indicates the subject of a finite verb: We went to the store.
All nouns have an article. This articel changes (along with adjectives) in case of an preposition.
Roughly:
1. case - no change
2. case
der => des (or ending "es").
der Vater
Das Auto des Vaters. The car of this father.
Das Auto meines Vaters. The car of my father.
die => der (or ending on "er")
Das Bild der Mutter. The picture of the mother.
Das Bild seiner Mutter. The pictor of his mother.
das => des (or ending on "s")
Das Haus des Mädchens. The house of the girl.
Der Hund des Mannes. The dog of this man.
3. case
prepositions bei, mit, nach, aus, zu, seit, von, .....
der => dem (+em)
die => der (+er)
das => dem (+em)
Ich gehe mit dem Mann (der Mann). / Ich gehe aus dem Haus (das Haus). Ich bin bei meiner Schwester. (die Schwester)
4. case
prepositions für, um, gegen, ohne, durch
der => den (+en)
die => die (+e)
das => das
Ich bin bei meiner Schwester. (die Schwester). Ich gehe um die Ecke. (die Ecke). Ich fahre durch den Tunnel. (der Tunnel).
3. and 4. case have prepositions which are used in both cases. You have to ask yourself: WO? (where?) = 3. case. WOHIN (where to) = 4. case.
3. case is "moving", 4. case is "standing still".
Ich stehe auf dem Stuhl. => 3. case. (I'm standing on the chair) - no move, you are standing still.
WO ? where are you standing. On the chair. Auf deM Stuhl.
BUT
Ich stelle mich auf den Stuhl => 4. case. (I'm going to stand on the chair) - movement
WOHIN? where to are you moving? Towards the chair. Auf deN Stuhl.