The Woman in White by Wilkie Collins may not be the first detective novel ever written, chronologically, but it is certainly one of the earliest. The earliest Western mystery novel is probably E. T. A. Hoffmann's Mademoiselle de Scudieri, which concerns a series of mysterious jewel thefts during the reign of King Louis XIV of France. In the story, the King convenes a special tribunal to investigate the thefts, and the mystery is ultimately solved by Mademoiselle Scudieri. This story probably helped provide some inspiration to Edgar Allen Poe for The Murders in the Rue Morgue in the 1840s, and later to Wilkie Collins for The Woman in White, published in 1860. Notably, Wilkie Collins followed this novel with another mystery, The Moonstone, published in 1868, which is without question Collins' masterpiece.
As to why mystery novels had not appeared earlier: between the 17th and 19th centuries, much of Western Europe underwent a great deal of population growth and concentration in large urban centers. The last plague in London ended in 1750, the population began to rise, and the industrial revolution was approaching its zenith. The common man could now make a living in centers of industry, rather than in agrarian settings, tied to the land. Cities such as London therefore experienced exponential growth--and a corresponding rise in crime.
Large groups of city dwellers required a more formal system of policing to maintain order. Up until this point, formal or informal watchmen were sufficient to keep order in urban centers. In 1797, however, the waterfront watchmen on the London docks were organized for the first time into a paid, dedicated constabulary.
By the early 19th century, maintaining law and order in Britain had become a national concern. In 1812, 1818, and 1821, Parliamentary committees were organized to address the question of law and order, and by the mid-1820s, Robert Peel, the British Home Secretary, had drafted a plan for a system of modern policing that would later become the Metropolitan Police Force.
The Metropolitan Police Force officially went into business in 1829, but even still, it wasn't until ten years later that the various groups of local watchmen still present in London were absorbed into the Force, and a unified system of policing came into being.
Because detectives didn't really exist, up to this point in history (in a formal sense, at least), it makes sense that modern detective fiction wasn't really written until around this time. By the late 19th century, of course, the Police were a professional and highly experienced British institution, and at the same time, Sir Arthur Conan Doyle began writing the brilliant Sherlock Holmes stories.
For more information about the history of policing and of detective work, please see the website of the London Metropolitan Police.