II Samuel - Chapter 7
"Oh, No, Not I. I Will Survive."
So here's David, living comfortably in his new palace, secure from his enemies on all sides. He turns to the prophet Nathan and says, "Why should I live in a house and G-d's Ark still be covered by a tent?" Nathan understood that David wanted to build the Temple and he agreed that it was a good idea.
G-d disagreed. He appeared to Nathan that night with a message for David. G-d said that His Presence had been in a tent since the Jews left Egypt and He never asked for a Temple. He said to tell David that he would not be the one to build it, but that his son, yet to be born, would be the one to build it. Furthermore, that son's dynasty would be eternal. Even when they deserved punishment, the kings descended from David would never lose the throne as Shaul had. (We see from here that Moshiach - the Messiah - must be descended not only from David, but specifically from his son Shlomo - Solomon.)
David was no doubt disappointed that G-d would not permit him to build the Temple, but his reaction was a prayer of thanks to G-d for treating him with so much kindness - not only him, but his descendants for all future generations!
The reason David was not permitted to build the Temple is not stated here, but it is in the Books of Kings and Chronicles. David was a warrior who had shed much blood. This may have been necessary and permitted, but the Temple, a house of peace, had to be built by someone who had not spilled blood.
The Yalkut Shimoni (II Samuel 145) spins that a little differently. So holy were David's actions, that his warfare was like sacrifices to G-d. Had David built the Temple, it would have been so holy that it could never have been destroyed. That may sound like a good thing, but when the Jews sinned, the only option would be to take it all out on them, rather than a house of wood and stone. The Temple had to be able to be destroyed so that the Jewish people could survive.