[Tex/LaTex] Reference table rows by automatic counter

cross-referencingnumberingtables

Problem

I have defined an environment to automatically number example sentences throughout my document. It uses the tabular environment and automatically numbers the first column of each row using a custom counter. I have reasons for not using lists or the theorem counter.

I want to label and reference a table row so that the number associated with the row is displayed. Using \label and \ref does not work. Is there some way to feed a function two args, a key and the current value of my counter, and later use the key to recall the other arg? Or is there another way to do what I want? Not breaking the labels and references for the rest of the document is ideal but not necessary.

(Non-)Working Example

\documentclass{article}
\usepackage{array} %don't know why this is needed; get csname error otherwise

% automatically number examples throughout document
\newcounter{exno}
\newenvironment{examples}
{
\begin{flushleft}
\begin{tabular}{>{(\stepcounter{exno}\theexno)}rl}
}
{
\end{tabular}
\end{flushleft}
}

\begin{document}

\section{Foo}
Here are some numbered example sentences.
\begin{examples}
  &Content of row 1 \label{row1} \\
  &Content of row 2 \label{row2}
\end{examples}
Now I want to get a 1 here: \ref{row1}. I want to get a 2 here: \ref{row2}.

\end{document}

Best Answer

In order for you to reference the counter like that you need to use \refstepcounter. This steps the counter, as well as telling LaTeX to use the supplied counter for the following reference.

Then you need to replace the \label's. They need to address directly to the counter. Therefore your example would be:

\documentclass{article}
\usepackage{array} %don't know why this is needed; get csname error otherwise

% automatically number examples throughout document
\newcounter{exno}
\newenvironment{examples}
{
\begin{flushleft}
\begin{tabular}{>{(\refstepcounter{exno}\theexno)}rl}
}
{
\end{tabular}
\end{flushleft}
}

\begin{document}

\section{Foo}
Here are some numbered example sentences.
\begin{examples}
  \label{row1} &Content of row 1 \\
  \label{row2} &Content of row 2
\end{examples}
Now I want to get a 1 here: \ref{row1}. I want to get a 2 here: \ref{row2}.

\end{document}

This will produce: example

Added: This also works by linking to the row by loading hyperref package.

Related Question