Error casting CHAR(1) SQL column as "char" in code - c#

I'm selecting from a SQL Server 2000 box CHAR(1) column called Combo_Label - it will always have a single A..Z character in there. During testing, it will convert the first 70 or so items with no problem, but then runs into a Invalid Cast Exception.
This is the problem line:
char comboLabel = (char)formCombo.Rows[j]["Combo_Label"];
This is a screenshot of the watch list showing some ways it can be evaluated.
Any thoughts as to why this occurs?

The database and the Db access APIs have no concept of char. Your CHAR(1) is mapped to string.
probably the most sensible option:
string comboLabel = (string)formCombo.Rows[j]["Combo_Label"];
but if you really want a char :
char comboLabel = ((string)formCombo.Rows[j]["Combo_Label"])[0];

The field is a string , you can do something like that but also need to consider if hte field is null or an emmpty string
char comboLabel = ((string)formCombo.Rows[j]["Combo_Label"])[0];

first convert that to a string, then get first character...
char comboLabel = formCombo.Rows[j]["Combo_Label"].ToString()[0];

Related

How to let user leave blank textboxes that are assigned as Char [duplicate]

I have what I think is an easy problem. For some reason the following code generates the exception, "String must be exactly one character long".
int n = 0;
foreach (char letter in charMsg)
{
// Get the integral value of the character.
int value = Convert.ToInt32(letter);
// Convert the decimal value to a hexadecimal value in string form.
string hexOutput = String.Format("{0:X}", value);
//Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);
charMsg[n] = Convert.ToChar(hexOutput);
n++;
}
The exception occurs at the charMsg[n] = Convert.ToChar(hexOutput); line. Why does it happen? When I check the values of CharMsg it seems to contain all of them properly, yet still throws an error at me.
UPDATE: I've solved this problem, it was my mistake. Sorry for bothering you.
OK, this was a really stupid mistake on my part. Point is, with my problem I'm not even supposed to do this as hex values clearly won't help me in any way.
What I am trying to do it to encrypt a message in an image. I've already encrypted the length of said message in last digits on each color channel of first pixel. Now I'm trying to put the very message in there. I lookt here: http://en.wikipedia.org/wiki/ASCII and said to myself without thinking that usung hexes would be a good idea. Can't belive I thought that.
Convert.ToChar( string s ), per the documentation requires a single character string, otherwise it throws a FormatException as you've noted. It is a rough, though more restrictive, equivalent of
public char string2char( string s )
{
return s[0] ;
}
Your code does the following:
Iterates over all the characters in some enumrable collection of characters.
For each such character, it...
Converts the char to an int. Hint: a char is an integral type: its an unsigned 16-bit integral value.
converts that value to a string containing a hex representation of the character in question. For most characters, that string will be at least two character in length: for instance, converting the space character (' ', 0x20) this way will give you the string "20".
You then try to convert that back to a char and replace the current item being iterated over. This is where your exception is thrown. One thing you should note here is that altering a collection being enumerated is likely to cause the enumerator to throw an exception.
What exactly are you trying to accomplish here. For instance, given a charMsg that consist of 3 characters, 'a', 'b' and 'c', what should happen. A clear problem statement helps us to help you.
Since printable unicode characters can be anywhere in range from 0x0000 to 0xFFFF, your hexOutput variable can hold more than one character - this is why error is thrown.
Convert.ToChar(string) would always check length a of string, and if it is not equal to 1 - it would throw. So it would not convert string 0x30 to hexadecimal number, and then to ascii representation, symbol 0.
Can you elaborate on what you are trying to archieve ?
Your hexOutput is a string, and I'm assuming charMsg is a character array. Suppose the first element in charMsg is 'p', or hex value 70. The documentation for Convert.ToChar(string) says it'll use just the first character of the string ('7'), but it's wrong. It'll throw this error. You can test this with a static example, like charMsg[n] = Convert.ToChar("70");. You'll get the same error.
Are you trying to replace characters with hex values? If so, you might try using a StringBuilder object instead of your array assignments.
Convert.ToChar(string) if it is empty string lead this error. instead use cchar()

ODataException: There is an unterminated string literal at position X, when a special character is passed as a filter parameter value

I am facing an issue while passing a filter parameter value which contains a special character i.e. '#' in odata query.
Example: "http://100.100.100.44:9999/DataMockService.svc/DataLineItemSet()?$expand=Sales&$filter=SoldTo/ZipCode eq '30931#'&$select=Sales/SalesNumber"
This is throwing the above mentioned error. In the back-end, I have a record which contains '30931#' in ZipCode column. When I remove # from the query, the query executes fine. I even tried encoding the '#' to '%23' but no use. Please help me with a workaround.
Thank You!
Use HtmlEncode
var encodedfilter = WebUtility.HtmlEncode(filter);
and then send encodedfilter as parameter

Identify problematic characters in a string

I want to be able to identify problematic characters in a string saved in my sql server using LINQ to Entities.
Problematic characters are characters which had problem in the encoding process.
This is an example of a problematic string : "testing�stringáאç".
In the above example only the � character is considered as problematic.
So for example the following string isn't considered problematic:"testingstringáאç".
How can I check this Varchar and identify that there are problematic chars in it?
Notice that my preferred solution is to identify it via a LINQ to entities query , but other solutions are also welcome - for example: some store procedure maybe?
I tried to play with Regex and with "LIKE" statement but with no success...
Check out the Encoding class.
It has a DecoderFallback Property and a EncoderFallback Property that lets you detect and substitute bad characters found during decoding.
.Net and NVARCHAR both use Unicode, so there is nothing inherently "problematic" (at least not for BMP characters).
So you first have to define what "problematic" in meant to mean:
characters are not mapped in target codepages
Simply convert between encodings and check whether data is lost:
CONVERT(NVARCHAR, CONVERT(VARCHAR, #originalNVarchar)) = #originalNVarchar
Note that you can use SQL Server collations using the COLLATE clause rather than using the default database collation.
characters cannot be displayed due to the fonts used
This cannot be easily done in .Net
You can do something like this:
DECLARE #StringWithProblem NVARCHAR(20) = N'This is '+NCHAR(8)+N'roblematic';
DECLARE #ProblemChars NVARCHAR(4000) = N'%['+NCHAR(0)+NCHAR(1)+NCHAR(8)+']%'; --list all problematic characters here, wrapped in %[]%
SELECT PATINDEX(#ProblemChars, #StringWithProblem), #StringWithProblem;
That gives you the index of the first problematic character or 0 if none is found.

How to avoid blank spaces after a value stored in database taken from textbox, asp.net?

whenever i insert a string value into database from textbox, in asp.net, a random number of blank spaces are stored after the string value in the database row? how to avoid it?
You can use the Trim() Function or you may also want to check your database set up.
If you have used char or nchar, you'll always be allocated the x amount of bytes space, and your string will be padded. To avoid this use varchar which will only store upto the character you sent.
If you send "test"
char(10) will store "test "
However varchar(10) will store "test"
Check the definition of the column in your database. Is it CHAR(x) or NCHAR(x)? Or VARCHAR(x) or NVARCHAR(x)?
If it's not VARCHAR or NVARCHAR, it's a fixed-length field, which means that there will always be spaces after it (assuming the length of your string is not exactly that of the field).
Unless you're coding from scratch, it may be a big deal to change the definition of a field in your database (and changing it won't remove spaces from all the existing rows already there). But that is probably what's happening.
This could also be happening if you're using CHAR(x) or NCHAR(x) somewhere along the way, in a stored procedure parameter or when creating parameters for a SqlCommand.
To trim spaces off a string, I like Habib's answer.
string content= TextBox1.Text.Trim();
Now store this content value into database.
If this doesn't help probably the issue is not at your application side.
You may additionally execute this query to remove the spaces-
UPDATE
your_table
SET
your_column = TRIM(your_column);
This will ensure you remove any spaces in all the values of the column.
Use trim() function in c# or SQL Query side ..
Ex:
String str = " C# ";
Console.WriteLine("Hello{0}World!", str);
string trStr = str.Trim();
textbox1.Text.Replace(" ","");
Maybe not the cleanest way to do it, but it should work
You can always use trim() option if you are using c#.
for example if your have a text string 'name', you can avoid any following blank spaces by :
string newstr = name.trim();
this will ensure that there are no blank spaces left at end of the string.

Specified Cast is not Valid - trying to cast a char

I am trying to cast a char as follows:
while (Reader.Read())
{
VM VMResult = new VM();
VMResult.status = (char)Reader["status"];
VMList.Add(VMResult);
}
Then comes the fun part: Specified Cast is not Valid.
VMResult.status is a char
The returned data is a char(1) in sql
I assume there must be a difference in the C# / SQL char terminology.
What do you think?
I assume there must be a difference in the C# / SQL char terminology.
That's correct. A char in sql server is a fixed length character string. It can be nullable.
A char in .net is a structure that represents a single character as a UTF-16 code unit. It cannot be null since its a structure
There is no fixed length character string .Net unless you consider a char array or byte array a fixed length string.
Since most of the .net ecosystem has better support for strings than chars, char arrays or byte arrays, you're much better off just using the string that gets returned for the char(x) fields.
If you know for a fact that Reader["status"] will always be a char (or you only want the first char), and the current type of Reader["status"] is a string you can always
VMResult.status = (!string.IsNullOrEmpty(Reader["status"])) ?
Reader["status"].ToCharArray()[0] : '';
EDIT: null checking ftw.
OK so you basically want to cast a string to a char, this is going to assume that your "status" value is a single character string:
VMResult.status = Reader["status"].ToString()[0];
this also assumes Reader[] does not already return a string (if it did then the ToString is not required) and that the value is not null.

Categories

Resources