Invalid Argument error for a function - c#

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

Related

Formatting a double within an interpolation

I have an interpolation where I need to format the variable to 2 places. The variable here is 'difference'
double difference = moneyLeft - trip;
Console.WriteLine($"Not enough money! {difference} needed.") ;
I have tried putting {0:f2} but doesn't seem to work. Currently it gives me a number like 418.2, where I need it to be 418.20. How can I fix it?
You can use the following code
double res = moneyLeft - trip;
string difference = String.Format("{0:0.00}", res); // say difference: 418.2
Console.WriteLine($"Not enough money! {difference} needed."); // Output: 418.20
There are two parts of the token syntax ({ }), the "before the colon", and the "after the colon".
When you're inside an interpolated string, the "before the colon" part is treated as code. That means if you use a variable name, it evaluates the value stored in that variable. If you give it a numeric literal, such as 0, it uses the value 0.
var input = 3.21;
string a = $"{input}"; // 3.21
string b = $"{0}"; // 0
0 In this case doesn't mean the "first positional argument after the template", such as is used in string.Format.
You already figured out that you should use f2 after the colon to get two decimal spots, but remember you can't use 0 before the colon, or else the value you'll be formatting is literally the number zero.
var input = 3.21267674;
// your first attempt
string a = $"{input}"; // 3.21267674
// your second attempt
string b = $"{0:f2}"; // 0.00
// the correct way
string c = $"{input:f2}"; // 3.21

Input string is not in correct format?

Ok, hey. I made a program for an in-game.. game. And I have it load data for a player from their own .txt on my computer. Whenever i try to command (.load) it tells me (at split[1] where it is converted to an int32) which is just a test to see if your bombs load, input string is not in correct format, heres the code:
StreamReader streemy = new StreamReader(#"c:\Usernames\" + player[m.GetInt(0)].username + ".txt");
string read = streemy.ReadToEnd();
if (!string.IsNullOrEmpty(read))
{
string[] split = read.Split('=');
player[m.GetInt(0)].bombs = Convert.ToInt32(split[1]);
Say(names[m.GetInt(0)].ToUpper() + ": You data has been loaded!");
streemy.Close();
}
else
{
Say(names[m.GetInt(0)].ToUpper() + ": Your data was empty :( Say '.save' to save your current data!");
}
.save Saves the data to the .txt, "names[m.GetInt(0)]" is their username, Say just tells them in the game the message. Thanks for your help! PS: player is a struct, which has ints like bombs.
I would suggest you to use Int32.TryParse instead of Convert.ToInt32.
So if the value is not valid integer then you can treat as 0 or no bomb.
int numberOfBombs = 0;
bool result = Int32.TryParse(value, out numberOfBombs);
now numberOfBombs would retain the actual value if there is valid integer field present otherwise it will be 0.
You must be getting a FormatException.
FormatException is thrown when the arguement is not in valid format.
I think that the value of split[1] is not a valid integer.
According to msdn.
FormatException : value does not consist of an optional sign followed by a sequence of digits (0 through 9).
Using the ToInt32(string) method is equivalent to passing value to the Int32.Parse(String) method. value is interpreted by using the formatting conventions of the current thread culture.
You can call the Int32.TryParse method instead. It returns a Boolean value that indicates whether the conversion succeeded or failed.

Converting between SQL char and C#

If I want to insert into a database column of type char(2) from C#.
What data type would I use in C#?
If using the following code:
private static SqlParameter addParameterValue(string parameterName, ? parameterValue, SqlCommand command)
{
SqlParameter parameter = new SqlParameter(parameterName, SqlDbType.Char);
parameter.Value = parameterValue;
command.Parameters.Add(parameter);
return parameter;
}
What type would I give to parameterValue?
I already have method like this when the parameterValue is of type string, so this could be a problem when telling the difference between SqlDbType.Char and SqlDbType.Varchar
char, varchar, nchar, nvarchar are actually strings
the size helps to determine how long the string is...
by the way
char has a fixed length, so if you want to have "1" in a char(2) the contents will be actual "1 "
varchar(2) will be "1"
the n part stands for unicode, so everything inside those fields will be in Unicode.
normally we use nvarchar to save some space on the data, as if you have a char(250) the database will always save the full length, as an empty varchar(250) will be nothing.
In our programming language we then use padding to do what char does, for example, in C#
"1".PadLeft(2);
"1".PadRight(2);
will output " 1" and "1 " respectively.
string will work fine if it is 2 characters or shorter
try using AddWithValue method and parce it as string,
it is only a one line. no need to have a seperate method.
command.Parameters.AddWithValue(parameterName, parameterValue);

Convert varchar to char ? how to fix error

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"]);

Convert String to Integer [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
how can I convert String to Int ?
Hi,
I have the following problem converting string to an integer:
string str = line.Substring(0,1);
//This picks an integer at offset 0 from string 'line'
So now string str contains a single integer in it. I am doing the following:
int i = Convert.ToInt32(str);
i should be printing an integer if I write the following statement right?
Console.WriteLine(i);
It compiles without any error but gives the following error on runtime:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
Any help please?
Rather than using Convert.ToInt32(string) you should consider using Int32.TryParse(string, out int) instead. The TryParse methods are there to help deal with user-provided input in a safer manner. The most likely cause of your error is that the substring you are returning has an invalid string representation of an integer value.
string str = line.Substring(0,1);
int i = -1;
if (Int32.TryParse(str, out i))
{
Console.WriteLine(i);
}
FormatException
value does not consist of an optional
sign followed by a sequence of digits
(0 through 9).
The exception that is thrown when the
format of an argument does not meet
the parameter specifications of the
invoked method.
You can use Int32.TryParse if you don't want to generate an exception like this.
Int32.TryParse: Converts the string representation of
a number to its 32-bit signed integer
equivalent. A return value indicates
whether the operation succeeded.
It's entirely possible there is some whitespace in there. Try running something akin to trim() (I'm not sure what language you're in) that will strip the white space. Also, try printing out the string to make sure you actually have the right part of it. We've all done that :)
It's likely that your input is not a valid format. Try this instead. If the number is not valid, it should output an error.
Keep in mind that the string should consist of an optional sign followed by a number.
string line = "23"; // or whatever.
string str = line.Substring(0,1);
int i = 0;
if (Int32.TryParse(str, out i)) {
Console.WriteLine(i);
} else {
Console.WriteLine ("Error converting '" + line + "', '" + str + "'.");
}
One thing you may be seeing is the user entering "-1" for example. If you do the substring(0,1) on that, you'll only get "-" which isn't really valid.
Are you sure that the value returned in str is an int, set a debug point if your using visual studio. Ive got a feeling your problem maybe that your not actually returning an integer. Try:
line.Trim().Substring(0,1);
This will remove any whitespace.

Categories

Resources