During the Mexican–American War, Gardner served under Major General Winfield Scott. He was promoted to Major in 1845 and commanded the 4th Artillery Regiment from 1846 to 1848. He was stationed at Fort Polk in Texas between July 29, 1846, and January 31, 1847. He fought at the Battle of Cerro Gordo on April 18, 1847, and was brevetted as a lieutenant colonel "for Gallant and Meritorious Conduct". He served in the Battle of Contreras on August 20, 1847, and was brevetted as a Colonel for his role on August 20, 1847, also "for Gallant and Meritorious Conduct". At the Battle of Cerro Gordon he commanded a company of the 7th Infantry, many of whom were killed or wounded during combat. He was later praised by his commanders, including Scott in his report of April 23, 1847, for his signal services.