The ruling, announced on Monday by the Lahore High Court, will not allow Sharif to run for Thursday's elections because of previous convictions.
Sharif's rival candidates from the by-election had argued that loan defaulters and people convicted of criminal charges could not contest election.
The Lahore High Court accepted their case.
An order issued by the court said: "Nawaz Sharif is not a qualified candidate to contest a by-election."
Shahbaz, Sharif's brother, also had a case referred to the chief election commissioner.
The court said Shahbaz could continue as chief minister until a final decision on his case was made.
"It's a political decision and we reject it. It is a conspiracy against democracy," Siddiqul Farouq, a spokesman for Sharif's PML-N, said.
The judges who gave the ruling were appointed by Pervez Musharraf, the Pakistani president, after he sacked dozens of judges under emergency rule.
'Musharraf's agenda'
Sharif's allies were furious, with dozens chanting "Go Musharraf, go" outside the court and angry lawmakers walking out of the provincial assembly in protest.
At least 100 Sharif supporters had burned tires in the street.
Ahsan Iqbal, a senior PML-N leader, said: "They are implementing Musharraf's agenda."
The decision is a major political setback for Sharif, making it impossible for the Sharif, the leader of a junior party in the governing coalition, to become prime minister unless the ban on his candidacy is overturned.
Sharif was also barred from running in February elections because of convictions related to his ouster in a 1999 coup, which was left by Musharraf.
Earlier this month, the nation's election commission effectively cleared him to run in by-elections after a tribunal set up to decide the matter failed to reach consensus.
Pervez Rasheed, Sharif's spokesman, said Sharif will appeal the decision before the elections.