1Ch 21:2 So David said to Joab and to the leaders of the people, "Go, number Israel from Beersheba to Dan, and bring the number of them to me that I may know it."
1Ch 21:7 And God was displeased with this thing; therefore He struck Israel.
8 So David said to God, "I have sinned greatly, because I have done this thing; but now, I pray, take away the iniquity of Your servant, for I have done very foolishly."
It was about the old sin of the devil --- pride. David got proud with his military might. Also, he found his safety and security in numbers. Apparently, Israel was punished too because they and their leader became proud of their might and number. Notice that before chapter 21, before this proud census, we read in chapters 18,19 and 20 the sterling military victorious of Israel. Apparently, it got into their heads!
David himself wrote (in the Septuagint this Psalm is attributed to David):
Ps 33:16 No king is saved by the multitude of an army; A mighty man is not delivered by great strength. 17 A horse is a vain hope for safety; Neither shall it deliver any by its great strength.
In addition, David, in his pride, might have also bypassed the prescribed ransom in Exodus 30:12:
Ex 30:12 "When you take the census of the children of Israel for their number, then every man shall give a ransom for himself to the LORD, when you number them, that there may be no plague among them when you number them.