Free Information Technology Magazines and eBooks

Monday, March 09, 2009

C#: Increment Letter

If not all, most of programmers had already experienced the need of incrementing numbers on their application. Incrementing numbers often used on generating unique internal control numbers but sometimes there is a need to use letter instead of number. A perfect working example was the module that I build to generate sequential filenames from 000001.txt... 99999.txt, A0001.txt, A0002.txt.. A1001.txt... B0001.txt up to Z9999.txt. Why use letter? on our case I was limited to just nine (9) characters filename so I have to use letters if file counter goes beyond 99,999 files/day.

You can increment letter in C# by:

int icol2 = "A";
icol2++; \\result will be B

Here is a function that i made to increment 999, A01 to Z99:

//Settings.Default.NewCounter - holds the current counter

private void getnewcounter()
{
int icounter;
int ifinalcount=0;
if (int.TryParse(Settings.Default.NewCounter.Substring(0, 1), out icounter) && Settings.Default.NewCounter.Substring(0, 1) != "9") //check if first char is numeric
{
ifinalcount = Convert.ToInt32(Settings.Default.NewCounter);
ifinalcount++;
Settings.Default.NewCounter = ifinalcount.ToString("00#");
}
else
{
if (Settings.Default.NewCounter.Substring(0, 1) != "9")
{
if (Settings.Default.NewCounter.Substring(1) != "99")
{
int icol2 = Convert.ToInt32(Settings.Default.NewCounter.Substring(1));
icol2++;
Settings.Default.NewCounter = Settings.Default.NewCounter.Substring(0, 1) + icol2.ToString("0#");
}
else
{
char scol1 = Convert.ToChar(Settings.Default.NewCounter.Substring(0, 1));
scol1++;
Settings.Default.NewCounter = scol1 + "01";
}
}
else
{
Settings.Default.NewCounter = "A01";
}
}
}


If you have questions please post it here... good luck!

2 comments:

Harry said...

i tried your function and i m kind of newbie. could you explain what the following is please?

//Settings.Default.NewCounter - holds the current counter

i cant get it to work. please help out by telling me what to put in it.

Fryan Valdez said...

hi harry,
Settings.Default.NewCounter is just an application settings or variable that holds the current counter value. The application needs to remember the current count and this is where the application setting/variable becomes handy.