I'm importing an excel file and i want to add the values to a database. in the database there is a type decimal(18, 5) and i want to add my value 0.00204 to that column in the database. My variable in my model class is of type decimal and i'm trying this code:
Convert.ToDecimal(items[7]);
but then i get the error that the input if not correct format.
items is of type object[]. How do i parse the value into a decimal?
all the others work just fine:
product.packSize = Convert.ToInt32(items[3]);
product.leadTime = Convert.ToString(items[4]);
product.generalAccessoryCategoryId = Convert.ToInt32(items[5]);
product.Company = Convert.ToString(items[6]);
product.Weight = Convert.ToDecimal(items[7]);
Check for the possible error conditions which may exist at any stage then once safe, extract the string:
decimal result;
if ((items!= null) &&
(items.Any()) &&
(items[7] != null) &&
(Decimal.TryParse(items[7].ToString(), out result))
product.Weight = result;
After a couple of comments and some investigation, I believe that the items[7] has characters which the convert is not expecting. I have updated my answer above.
decimal result;
Decimal.TryParse("0a00204", out result); // Returns false
EDIT
If you are dealing with a culture issue, you can use this TryParse(Object, NumberStyles, IFormatProvider, out decimal) and include your culture (using en-GB as an example):
decimal.TryParse(items[7], NumberStyles.Any, CultureInfo.GetCultureInfo("en-GB"), out product.Weight);
If the item variables have default values, you can use TryParse which will replace the value if it can be parsed, or leave it as the default. Otherwise you can use the result from TryParse (true if it succeeds, false if it fails) to determine whether you need to set the value. For example:
decimal.TryParse(items[7], out product.Weight)
OR
if(!decimal.TryParse(items[7], out product.Weight))
{
product.Weight = (decimal)0;
}
It may also help to call the ToString() method on the object in the array, as sometimes the parse function can have more trouble with interpreting objects than their String reprentations.
if(items != null && items[7] != null){
product.Weight = decimal.Parse(items[7].ToString());
}
Related
I want to save the information entered in ASP.NET to the database and display it in GridView but the information that needs to be entered is dropdownlist selected.
The IDs of the elections held are kept.
int birim =Convert.ToInt32(DDLbirim.SelectedValue);
and
int birim=(int)DDLbirim.SelectedValue;
I write but in the form of an error. How can I help you track a way?
There are several ways to convert a string to int.
Convert.ToInt32 is one of them, but like int.Parse, it raises an exception if your string is not a numeric
To avoid the exception, you can use TryParse
The TryParse method is like the Parse or Convert.ToInt32 method, except the TryParse method does not throw an exception if the conversion fails.
bool isSuccees= Int32.TryParse(DDLbirim.SelectedValue, out birim );
I think your DDLbirim.SelectedValue is not a valid int so it can not cast it to a int hence the exception.
I would do an int.TryParse to check if the value is a valid int.
bool successfullyParsed = int.TryParse(DDLbirim.SelectedValue, out birim);
if (successfullyParsed){
// ...
}
The selectedValue is null when the dropdown isn't selected as valid. Else, as long as each item in the dropdown have a valid value, it will return as proper
The value is of type object, as it can store any type available.
Make sure that the values being set in the designer or backend are indeed integer and not string. Good way to identify would be as
if (ddlBrim.SelectedIndex >=0) {
var value = ddlBrim.SelectedValue;
// Inspect value in debugger to validate at this point
int intValue = -1;
if (Int32.TryParse(ddlBrim.SelectedValue, out intValue) {
// use the result value here
}
}
If DDLbirim.SelectedValue is null or if contains non-integer value you have to use TyrParse. TryParse handles nulls and invalid strings
int birim=0;
if (int.TryParse(DDLbirim.SelectedValue, out birim)){
}
Please make sure that you correctly bind the dropdownlist i.e. with displayMember, ValueMember (field must be parsable to the integer value), and Datasource.
Once it's fine, you can try to parse it.
AS part of an import I'm writing I'm using parameterised values, however the database i'm exporting to cannot handle NULL values, so I need to find a way to handle NULL values.
The closest I've gotten is:
if (tenantexportReader.GetSqlMoney(8).ToDecimal().Equals(null))
{
tenantimportCommand.Parameters["PRICEFINAL"].Value = "0.00";
}
else
{
tenantimportCommand.Parameters["PRICEFINAL"].Value = tenantexportReader.GetSqlMoney(8).ToDecimal();
}
and A similar thing with SQLDateTime
if (tenantexportReader.GetDateTime(9).ToShortDateString().Equals(null))
{
tenantimportCommand.Parameters["TENSDATE"].Value = "0.00";
}
else
{
tenantimportCommand.Parameters["TENSDATE"].Value = tenantexportReader.GetDateTime(9).ToShortDateString();
}
However this does not appear to work, instead I receive the following:
Message=Data is Null. This method or property cannot be called on Null values.
Instead of
if (tenantexportReader.GetSqlMoney(8).ToDecimal().Equals(null))
you should probably use
if (tenantexportReader.IsDbNull(8))
Since the value in the database is NULL (which is DbNull.Value in c#), I assume that GetSqlMoney and GetSqlDateTime throw the exception you received. DbNull.Value cannot be converted to SqlMoney or DateTime.
Check if the value is null via IsDbNull before calling GetSqlMoney or GetSqlDateTime.
So your final if statements should look something like this:
if (tenantexportReader.IsDbNull(8))
{
tenantimportCommand.Parameters["PRICEASK"].Value = "0.00";
}
else
{
tenantimportCommand.Parameters["PRICEFINAL"].Value = tenantexportReader.GetSqlMoney(8).ToDecimal();
}
Why would you assign a string to a monetary value???
Probably what you would want to do is like this:
var priceFinal = tenantexportReader.GetSqlMoney(8);
tenantimportCommand.Parameters["PRICEFINAL"].Value = (decimal)(priceFinal.IsNull ? 0 : priceFinal);
I really don't understand why you set it to "0.00" (string) when it is null and to a decimal value when it is not null.
And also for date/datetime values, again, why do you ever use string conversions and invite errors? Simply pass a date as a datetime.
I just want to know, whether a variable contains a positive integer value.
Currently I am doing:
int APPOeeVersion =
Convert.ToInt32(ConfigurationManager.AppSettings["OEEVersion"]);
Here i just want to know whether APPOeeVersion Contains Int value or not. If not Need to show a error message as it is invalid format. Please help me out i have checked with several forums but not find exact solution.
Use int.TryParse, It will not raise an exception in case of failure and would give you bool value back if parsing was successful/unsuccessful.
string str = "1234";
int APPOeeVersion;
if (int.TryParse(str, out APPOeeVersion))
{
//parsing successful
}
else
{
//not an integer
}
If parsing is successful you will get the value of parsed string in your out parameter.
For checking a positive number and parsing you can have the check like:
if (int.TryParse(str, out APPOeeVersion) && APPOeeVersion > 0)
If you want to test for a positive integer, then you might need to use uint.TryParse since int.TryParse will allow negative values.
uint appoEeVersion;
var oeeVersionValue = ConfigurationManager.AppSettings["OEEVersion"];
if(!uint.TryParse(OEEVersionValue , out appoEeVersion))
{
// Error, not a positive integer
}
else
{
// Success, user value
}
int.TryParse would be the method: http://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx
int APPOeeVersion;
if(!int.TryParse(ConfigurationManager.AppSettings["OEEVersion"], out APPOeeVersion) || APPOeeVersion < 0){
//throw error
}
//use variable APPOeeVersion
I'm a little confused by your wording. Do you mean the variable is an integer or contains an integer?
If the former, then the solutions posted will work fine.
Are you guaranteed that the variable will only ever be an integer with no decimal notation (eg: 2 vs 2.0)? If not, you might need to use decimal.parse instead.
Integer parsing will fail on the other decimal values since they are not valid integers.
Decimal APPOeeVersion;
if (Decimal.TryParse(input,out APPOeeVersion))
{
Console.WriteLine("Successfully parse: {0} to {1}", input, APPOeeVersion);
}
else
{
Console.WriteLine("Failed to parse {0}", input);
}
Console.Write("\nEnter a number to test: ");
Then then use additional logic to ensure that the result is positive.
If you want to know whether it contains an integer, then a regular expression like the ones found here will work.
Maybe I'm just dumb or overthinking this, but it seems like you have to give a few more constraints
I've just tried TryParse, and am new to C# and just trying to understand everything, and then hopefully best practices...
Syntactically this works:
double number = Double.Parse(C.ReadLine());
Does TryParse only return a boolean, true if parse succeeds?
When I do this:
double number;
bool b = Double.TryParse(C.ReadLine(), out number);
number is the parsed input, from C.ReadLine(), as expected, everything works. Is this how TryParse is normally used? Trying to be efficient, appreciate advice like this.
Any advice on approach welcome, plus info on online resources for Try(things).
You use TryParse when it may fail, and you don't want your code to throw an exception.
For example
if (!Double.TryParse(someinput, out number))
{
Console.WriteLine("Please input a valid number");
}
Parse will return the double value if it succeeds and throws an exception otherwise. TryParse will return a boolean value representing the success of the operation and if it does succeed, it fills in the parsed value in the out argument you pass to it. It will never throw an exception.
In general, you should use TryParse when you expect the input string to not be a valid number and you have the logic to handle it (and display an error message, for instance).
If you don't expect the input string to be anything except a valid double you should use Parse.
The only differnce is that TryParse won't thow an exception if it can't parse the double.
This is handy when you want to assign a default value or ignore the value in your code
Example:
double number;
if (Double.TryParse(C.ReadLine(), out number))
{
// this is a double so all good
}
else
{
// not a valid double.
}
Example:
double number;
progressBar.Value = Double.TryParse(C.ReadLine(), out number) ? number : 4.0;
// If number is a valid double, set progressbar, esle set default value of 4.0
You also asked aboy TyrParse on Enum, this can be done like this
DayOfWeek fav;
if (Enum.TryParse<DayOfWeek>(Console.ReadLine(), out fav))
{
// parsed
}
Why does
Convert.ToBoolean("1")
throw a System.FormatException?
How should I proceed with this conversion?
Yes, this is as documented:
[throws] FormatException [if] value is not equal to TrueString or FalseString.
TrueString is "True" and FalseString is "False".
If you want to detect whether a string is "1" or not, use this code:
bool foo = text == "1";
Depends on what you want. Perhaps
var result = Convert.ToInt32(yourstirng) != 0
assuming any number but 0 is true. Otherwise a simple comparison would work.
var result = yourstirng == "1"
The parameter must be equal to either Boolean.TrueString or Boolean.FalseString. The values of these strings are "True" and "False", respectively. See MSDN.
The string value "1" is obviously not equal to "True" or "False".
The problem is, that youre giving a String here, not a number. It cant convert the String "1" to true, but the int 1.
Convert.ToBoolean(1);
should work.
When converting to Boolean it is best to use your own routine, where you handle all cases. .net Convert.ToBoolean isn't a practical routine, it is one of those function where you have to explain why it doesn't work.
I know this is old, but in case someone searches... simply do this:
Convert.ToBoolean(Convert.ToInt16("1")) works just fine. Not pretty, but needs be.
Another solution is to use an Extension Method on the string object. I used this technique in a case where I had to parse CSV files that had different strings that had to be converted to boolean values depending on their source and format.
public static class StringExtensions
{
public static bool ToBool(this string value,string trueValue)
{
if (value == trueValue)
{
return true;
}
else
{
return false;
}
}
}
This would be called like so...
MyProperty = CsvColumn[6].ToBool("1");
If you want, the truevalue parameter could be a string array if you needed to compare multiple values (like n/a, na, none) and you could add in false values if you want to further restrict it or use nullable types.