I get this error below when I want to convert DRMKOD to char ?
[ varchar(1) coloumn ] is the type of "DRMKOD" column on sql table.
String must be exactly one character
long. at
System.Convert.ToChar(String value,
IFormatProvider provider) at
System.String.System.IConvertible.ToChar(IFormatProvider
provider) at
System.Convert.ToChar(Object value)
entity.DrmKod = Convert.ToChar(dt.Rows[i]["DRMKOD"]);
public char DrmKod
{
get { return _DrmKod; }
set { _DrmKod = value; }
}
The two types are not compatible. varchar is a string, char is a single character.
Convert the result to a string, and then get the first character using str[0] (assuming the string even has any characters and is not null!).
What is the value that is dt.Rows[i]["DRMKOD"]? I can only think that it is something that is either empty or null.
VARCHAR(1) implies that it can be NULL or String.Empty.
if (dt.Rows[i].IsNull("DRMKOD") || (dt.Rows[i]["DRMKOD"] == String.Empty))
entity.DrmKod = ' '
else
entity.DrmKod = Convert.ToChar(dt.Rows[i]["DRMKOD"]);
Related
I have a JArray that contains null values. And while I'm doing string.Join, null values are getting converted into empty string.
Original array values:
[
null,
null,
"America/Boise",
false,
"2021-02-04T06:51:33.9686227Z"
]
String.Join:
var val = $"('{string.Join("','", valuesArray)}')";
Current Result:
"('','','America/Boise','False','2/4/2021 6:51:33 AM')"
Expected Result:
"(null,null,'America/Boise',False,'2/4/2021 6:51:33 AM')"
Producing Example:
https://dotnetfiddle.net/5nRTyL
How do I get the expected result using string.Join?
null values in a JArray are stored as JTokens with a JTokenType of Null. So you'll need to check for this and convert them to the string "null". Secondly, since you only want to quote some of the values, you should not put the quotes in the separator value when you join them, but instead only quote the values that need it based on their types.
Define the following helper function:
string TokenToString(JToken token)
{
switch (token.Type)
{
case JTokenType.Null:
return "null";
case JTokenType.Date:
case JTokenType.String:
return $"'{token}'";
default:
return token.ToString();
}
}
Then you can get the result you want like this:
string val = $"({string.Join(",", valuesArray.Select(v => TokenToString(v)))})";
Working demo here: https://dotnetfiddle.net/Q62Uck
Because that's how it was designed. See the documentation for String.Join:
If separator is null, an empty string (String.Empty) is used instead. If any element in value is null, an empty string is used instead.
just replace "''" to "null".
var val = $"('{string.Join("','", valuesArray)}')".Replace("''", "null");
Function
MouldingDetail_UpdateDetails(string mouldItem, string mouldQty, int core, int freerider, decimal plate, string plant, string systemMode)
after passing
MouldingDetail_UpdateDetails( "AX5M211531", '1', 1, 1, '0.5', "CMLD1", string.Empty) when I pass the following as values it shows "invalid arguments"
This is the method's signature:
MouldingDetail_UpdateDetails(
string,
string,
int,
int,
decimal,
string,
string
)
Yet, you're passing:
MouldingDetail_UpdateDetails(
"AX5M211531" (string), // Good
'1' (char), // Wrong! This is supposed to be a string! use "1" instead
1 (int), // Good
1 (int), // Good
'0.5' (invalid char), // Wrong! This shouldn't even compile. Use 0.5M without the single quotes
"CMLD1" (string), // Good
string.Empty (string) // Good
);
'1' isn't a valid string, it's a char instead.
For a proper understanding please read - https://msdn.microsoft.com/en-us/library/cs7y5x0x(v=vs.90).aspx
I need to extract a variable length decimal number from a string using c# and .NET. The input string is like $PTNTHPR,352.5,N,2.3,N,4.6,N,16*. I need the first occurrence of decimal number, i.e the 352.5 part. The numerical value ranges from 0.0 to 360.0 and I need that number from that string.
I searched a lot and got solution for a fixed length sub string but here I have variable length to extract. I have not tried with any code yet.
If it is always in this format you can use String.Split and decimal.Parse
var data = #"$PTNTHPR,352.5,N,2.3,N,4.6,N,16*";
var d = decimal.Parse(data.Split(new[]{','})[1]);
Console.WriteLine(d);
This is just a sample code to guide you. You should add additional exception handling logic to this, Also consider using decimal.TryParse
If you want to find the first occurance of decimal value you split the string and parse them one by one.
var data = #"$PTNTHPR,352.5,N,2.3,N,4.6,N,16*";
var splited = data.Split(new[]{','});
decimal? value = null;
foreach (var part in splited)
{
decimal parsed;
if (decimal.TryParse(part, out parsed))
{
value = parsed;
break;
}
}
Console.WriteLine(value);
First occurence in any of the tokens? Use String.Split to separate them and LINQ to find the first. You can use decimal.TryParse to check if it's parsable:
decimal? firstParsableToken = "$PTNTHPR,352.5,N,2.3,N,4.6,N,16*".Split(',')
.Select(s => s.TryGetDecimal(NumberFormatInfo.InvariantInfo))
.FirstOrDefault(d => d.HasValue);
Used this simple extension method to parse it to decimal?:
public static decimal? TryGetDecimal(this string item, IFormatProvider formatProvider = null, NumberStyles nStyles = NumberStyles.Any)
{
if (formatProvider == null) formatProvider = NumberFormatInfo.CurrentInfo;
decimal d = 0m;
bool success = decimal.TryParse(item, nStyles, formatProvider, out d);
if (success)
return d;
else
return null;
}
If the string is always comma separated, can you not use string.Split() to get each section, then use double.TryParse() to test if that part is numeric?
public static class Helper
{
public static string MyExtract(this string s)
{
return s.Split(',').First(str => Regex.IsMatch(str, #"[0-9.,]"));
}
}
Use it like this: string str = "$PTNTHPR,352.5,N,2.3,N,4.6,N,16*".MyExtract();
Then convert it to double/decimal if you need it.
There is two variable was assigned the value of "003" and "00 3". And it was convert to byte[] as below.
Before:
myStr1 = "003"; // valid, there is no blank inserted.
myStr2 = "00 3"; // invalid, there is one blank character or multi blanks character inserted.
After converted by convert(), if there are blank characters found, the source string will be convert to byte array.
myVal1 = "3"; // valid after convert
myVal2[0] = 0; // invalid, since the source myStr2 is invalid.
myVal2[1] = 1; // same as above.
And now I need determine the source string is valid or invalid based on the converted result. I dont' know how to say the result is an byte array. Could you please give me some advice. Thanks in advance.
input string type source value as SourVal
if (ResultVal is Byte Array) // how to translate the statement to C# code?
SourVal is Invalid;
else if (ResultVal is still String type) // how to translate the statement to C# code?
SourVal is valid;
ps: I failed to try the methods of typeof() and gettype() at my practice. I don't know how to use the methods. Or there is other better method for my validation.
maybe use:
if (ResultVal is byte[]) {
// SourVal is Invalid;
} else if ( ResultVal is String ) {
//SourVal is valid;
}
Try using IsWhiteSpace
//Check the String for Blank spaces if found then don't convert
if(!str.Contains(" "))
{
//use the convert method
}
else
{
//Write Message for an Invalid String
}
I have an enum
public enum BookType
{
Old = 'O',
New = 'N',
All = 'B'
}
What I need to do is get the value of the char in the enum. For example if the enum is set to:
BookType bt = BookType.New
I need to get the value of new "N"
string val = (???)bt;
I need val = N
What is the best way to do this? If it was an int easy, just cast to int.
Thanks.
The values associated with your enum are still ints, you've just set using a character literal. If you want to recover this value as a string, you can cast the enum value to a char and then convert that to a string:
string val = ((char)bt).ToString();
You can just cast to char.
After casting to char, you'll need to call ToString() to convert the char to a string:
string val = ((char)bt).ToString();