Solution 1:

I don't think I understood what you wrote. Look, if $g\in Z(D_{2n})$, then $gh=hg$ for every $h\in D_{2n}$. In particular it is true for $h=a$ and $h=b$. This proves the half you stated above.

Conversely, suppose $ga=ag$ and $gb=bg$. First note that $ga^i=a^ig$ for all $1\leq i<n$ (you can prove this by induction if you like: $ga^{i}=aga^{i-1}$). Now, any $h\in D_{2n}$ has the form $h=a^ib^j$, $0\leq i<n$, $0\leq j\leq 1$. So, $$gh=ga^ib^j=a^igb^j=a^ib^jg=hg.$$ This completes the proof.

This gives a fast way to prove that $Z(D_{2n})$ is nontrivial only if $n=2k$ is even. In this case, either $k=1$ and $D_4=\mathbb{Z}_2\times\mathbb{Z}_2$ is abelian, or $Z(D_{2n})=\langle a^k\rangle$. To see this, suppose $g\in Z(D_{2n})\backslash\{1\}$. We consider two cases:

Case 1: $g=a^k$. Then $g$ commutes with $a$. Next we compute $gb=a^kb$, and $bg=ba^k=a^{-k}b$. Since $bg=gb$, we must have $a^{k}b=a^{-k}b$. This forces $k\equiv -k$ (mod $n$), so $n=2k$ is even.

Case 2: $g=a^kb$. Then $ag=a^{i+1}b$ and $ga=a^iba=a^{i-1}b$, so $i+1\equiv i-1$ (mod $n$). This forces $n=2$, and $D_{2n}=D_4=\mathbb{Z}_2\times\mathbb{Z}_2$.

Putting these cases together, $Z(D_{2n})=1$ if $n$ is odd; if $n=2$, $D_4=Z(D_4)$ is abelian; if $n=2k>2$, then $Z(D_{2n})=\langle a^k\rangle$.