2

I have a "phone" area in my database and data type is char(11).

I need to make a conversion in ASP.NET C# as below:

char PhoneNumber = char.Parse((item.FindControl("TxtPhoneNumber") as TextBox).Text);

but I get an error:

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code

Additional information: String must be exactly one character long.

How can I resolve this error?

1
  • Please have a look at data type mapping between database and c# learn.microsoft.com/en-us/dotnet/framework/data/adonet/… This should be similar for other databases (oracle, mysql, etc) In c# char is a type which represents one character. You cannot parse a string into one character except the string is exactly one char long (as the error message mentions). Commented Jan 13, 2018 at 17:57

2 Answers 2

1

char.Parse shall take a string of length 1 and shall return a char value. If you want to convert your textboxt content to char array you can do like below:

string PhoneNumberstr = (item.FindControl("TxtPhoneNumber") as TextBox).Text);
char[] PhoneNumber = PhoneNumberstr.ToCharArray();
Sign up to request clarification or add additional context in comments.

1 Comment

The answer shows how to convert a string to char array, but how are you going to save the char array in the database CHAR(11) field? You will have to do another conversion back to string. So what's the point? Just send the original string directly to the database.
1

You don't need to convert it. The database CHAR type is a string type. The only difference is that the CHAR length is fixed (in your case 11 characters).

So just send your string as is:

string PhoneNumber = (item.FindControl("TxtPhoneNumber") as TextBox).Text;

Note: The database CHAR type is not the same as the char type in c#, which is used to store one single character.

1 Comment

This is the actual answer to the OP's question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.