# Using counter within database

I try to add a countervalue into a database. But if the database content will be printed, the value is allways the maximum value. I have a simple code example

\documentclass[11pt,titlepage,a4paper]{article}
\usepackage{datatool}

\DTLnewdb{testDB}
\newcounter{couter1}

\begin{document}

%first row
\setcounter{couter1}{1}
\DTLnewrow{testDB}%
\DTLnewdbentry{testDB}{Field1}{cnt: \arabic{couter1}}%
\stepcounter{couter1}
\DTLnewdbentry{testDB}{Field2}{cnt: \arabic{couter1}}%

%second row
\stepcounter{couter1}
\DTLnewrow{testDB}%
\DTLnewdbentry{testDB}{Field1}{cnt: \arabic{couter1}}%
\stepcounter{couter1}
\DTLnewdbentry{testDB}{Field2}{cnt: \arabic{couter1}}%

%display content of the database
\DTLdisplaydb{testDB}

\end{document}


The result shuld just look like:

1 | 2
3 | 4


Can anyone help me?

Section 5.1 explains that values given as arguments to \DTLnewdbentry are not expanded, so you get cnt: \arabic{couter1} in all cases. But the manual also suggests a workaround, with \dtlexpandnewvalue and \dtlnoexpandnewvalue.

\documentclass[11pt,titlepage,a4paper]{article}
\usepackage{datatool}

\DTLnewdb{testDB}
\newcounter{couter1}

\begin{document}

%first row
\setcounter{couter1}{1}
% we want to expand values
\dtlexpandnewvalue
\DTLnewrow{testDB}%
\DTLnewdbentry{testDB}{Field1}{cnt: \arabic{couter1}}%
\stepcounter{couter1}
\DTLnewdbentry{testDB}{Field2}{cnt: \arabic{couter1}}%

%second row
\stepcounter{couter1}
\DTLnewrow{testDB}%
\DTLnewdbentry{testDB}{Field1}{cnt: \arabic{couter1}}%
\stepcounter{couter1}
\DTLnewdbentry{testDB}{Field2}{cnt: \arabic{couter1}}%
% revert to the default
\dtlnoexpandnewvalue

%display content of the database
\DTLdisplaydb{testDB}

\end{document}


Be careful that in this way everything will be fully expanded and sometimes this is not wanted. A single control sequence such as \textbf can break havoc in this context, but simply preceding it with \noexpand will do; a longer (balanced with respect to braces) list of tokens not to be expanded can be given as argument to \unexpanded.

• Thank you. This solution is exactly what i was looking for. – Martin Bachmann Sep 3 '13 at 17:33