Automatic Table Row Numbers in LaTeX

I am writing my thesis in LaTeX at the moment, and I highly recommend it. The main advantage is the ability to mark a document up with tags, such as section and chapter numbers, which count automatically. This means that it is possible to move parts of the document around transparently, and all the references numbers will change.

I was compiling a table with numbered rows, and after moving rows a few times, decided it might be handy to be able to automatically number the rows. The code below displays the arabic numerals, but it is easy enough to choose other values.

%Declare the Counter, then initialise it.
\newcounter{rownum}
\setcounter{rownum}{0}
% Table
\begin{table}[htbp]
\caption{Table Caption}
\begin{center}
\begin{tabular}{|c||l|l|}
\hline
\textbf{\#} & \textbf{Column1} & \textbf{Column2} \\ \hline \hline
%Increment then display the counter value
\addtocounter{rownum}{1}\arabic{rownum}. & Row1Cell2 & Row1Cell3 \\ \hline
\addtocounter{rownum}{1}\arabic{rownum}. & Row2Cell2 & Row2Cell3 \\ \hline
\addtocounter{rownum}{1}\arabic{rownum}. & Row3Cell2 & Row3Cell3 \\ \hline
\end{tabular}
\end{center}
\label{tablelabel}
\end{table}%

PDF output looks like this:
table

I suspect this can be shortened using \newcommand , but I haven’t done that yet.

Some Counter Documentation.

Update: A Comment from Stefan_T corrected a typo in the script. He also mentions that the \centering command might be better than using \begin{centre}.
For those of you who are interested, here is an article on the centering vs. centre issue. My thanks go out to Stefan_T for his help!

Popularity: 23% [?]

This entry was written by Alex, posted on 10/03/2009 at 18:28, filed under LaTeX and tagged , , , , , , . Leave a comment or view the discussion at the permalink.