Home > C# Programming Tips > Check The String is a valid Excel CellName or not using c#

Check The String is a valid Excel CellName or not using c#

If you want to check the validity of name of cells you enterd
This function checks given string is a range addres or not
A1:A13- valid
A1:B12 valid
A1:A-not valid
A1:aa not valid
1A:b1 –not valid.

public bool checkcellRangeValidity(string inputrange)
{ bool valid = true;
string[] parts = inputrange.Split(':');
if (parts.Length == 2)
{
if (!((validcell(parts[0])) && (validcell(parts[1]))))
valid = false;
}
else //only one part or more parts on both sides of ':'
{
valid = false;
}
return valid;
}

Give string is a valid cell or not
A1: valid
A-not valid
1 not valid
1A not valid

public bool validcell(string inputcell)
{
bool valid = true;

int count = 0;
int digitscount = 0;
int lettercount = 0;

foreach (char c in inputcell)
{
if (char.IsDigit(c))
digitscount++;

if (char.IsLetter(c))
lettercount++;

if (!char.IsLetterOrDigit(c))
{
valid = false;
break;
}

if (count == 0) //means the very first char should be letter
{
count++;
if (!char.IsLetter(c))
{
valid = false;
break;
}

}
}

if (valid)
{ //chk only if the conditions are true till
if (!((digitscount >= 1) && (lettercount >= 1)))
{
// the cell is lagging either a no or a letter

valid = false;
}
}

return valid;
}

Advertisements
Categories: C# Programming Tips Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: