My problem is, when I want to convert (result[i].JobOrder) to int.I have a string 120100 in (result[i].JobOrder). In return I get not integer but something like "0x0001d524". And I could not understand why.
for (int i = 0; i < result.Count; i++)
{
if (Convert.ToInt32(result[i].JobOrder) > maxJobOrder)
{
maxJobOrder = Convert.ToInt32(result[i].JobOrder);
}
}
Your code works, but you have set your debugger to display integers in hexadecimal. The value 0x0001d524 is the hexadecimal representation of the integer 120100.
This is not an error in the program, but a configuration option for your IDE. If you use Visual Studio, you can change this setting by pressing the "Hex" button in the "Debug" toolbar.
As an aside, if you are using C# 3 or newer you can simplify your code by using the Max method to find the maximum instead of looping:
maxJobOrder = result.Max(x => int.Parse(x.JobOrder));
Try to use
Int32.TryParse
see
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
try to replace Convert.ToInt32 with int.parse()
The suggestion to use int.parse is slightly flawed.
int.parse will throw one of the following exception whenever it fails. And it only accepts strings as input to convert.
ArgumentNullException
FormatException
OverflowException
Convert.ToInt32 will throw one of the following exceptions whenever it fails. In addition,
it allows passing of null values, however this means that it returns a 0 as the output value, and it also handles multiple datatypes to be converted into an integer.
FormatException
OverflowException
int.TryParse will not throw any exceptions, however, it will return a 0 as the output value as the method returns false, and it only accepts strings as input to convert.
You should choose the right tool for the job to prevent any issues in the integrity of your solution.
Related
I'm fairly new to programming and have been racking my brains out trying to fix this error. Any help would be greatly appreciated.
string sBipLength = aPart.get_Parameter(BuiltInParameter.FABRICATION_PART_LENGTH).AsValueString();
double dParse2 = Double.Parse(sBipLength);
sBipLength = (dParse2 / aPart.CenterlineLength).ToString();
I am wanting to return the AsValueString and convert it to a format to where i can divide.
First, I'd set a breakpoint at the first line, and step through (hit F10). Then hover over sBitLength to see what the value is that you're getting. I'm supposing that what you're getting isn't a valid double.
Also, it's generally recommended that you use Double.TryParse if you don't know for certain what the format will be. (This isn't always the case, but TryParse is safer.)
string sBipLength = aPart.get_Parameter(BuiltInParameter.FABRICATION_PART_LENGTH).AsValueString();
double dParse2 = 0;
if(!Double.TryParse(sBipLength, out dParse2))//syntax edit
{
// handle any errors here when applicable
}
else
{
sBipLength = (dParse2 / aPart.CenterlineLength).ToString();
}
There are a lot of different ways you could structure the TryParse block, and you'll probably have to make modifications to fit it into your current code. This is just an example of it in action. (Important note: the out keyword sort of acts as another return in a sense. Double.TryParse returns a bool, but that out gives you the double assuming the string is valid.)
I am using C#, .NET 3.5. I have following code
string.Compare("KHA","KTB",true)
It returned value 1. This means KHA > KTB in alphabet order.
I expect it returns value -1.
Can anyone help me fix this?
Yes, all of you are right. It's because of the Culture. I add CultureInfo.InvariantCulture and it is solved.
Thanks all!
strig.Compare returns the relative position in the sort order. Since 'H' comes before 'T' that is why you are getting 1
Its should return -1, See the image
There must be something wrong going on with your compiler, it should return -1 and your understanding for the string.Compare is right.
You may try using CultureInfo.InvariantCulture:
int value = string.Compare("KHA", "KTB", true,CultureInfo.InvariantCulture);
The call string.Compare("KHA","KTB",true) should return -1 as expected. It does when I test it.
If you get any other result, you either are using other strings, or you have a default culture where 'T' is actually considered to come before 'H'.
For the latter case, you can specify a culture info in the call:
string.Compare("KHA", "KHB", true, CultureInfo.InvariantCulture)
If you are really getting 1 against string.Compare("KHA","KTB",true) then your system's current culture must be making an effect. Check the documentation of String.Compare. Also check the best practices of comparing a string here.
I am getting the error "System.FormatException : input string was not correct".
TextBox2.Text = objnm.rupees(Convert.ToInt64(Convert.ToDecimal(txtWOrds.Text.Trim())));
First, you don't need to convert it to decimal (Convert.ToDecimal) and then to Int64 (Convert.ToIn64).
Second, if txtWOrds.Text is not a number or is empty, than you will get this exception. Make sure that it is a number.
Third, if your value is a number, than your problem likes somewhere in objnm.rupees()
You should check the input in case its empty, like string.IsNullOrEmpty(txtWOrds.Text) then proceed with the parsing of the contents of the textbox.
Also you should be using TryParse which evaluates if the text can be parsed and if true you can use the value of the out parameter of this method.
In your case it could fail if the TextBox is empty.
Also if its anything related to money/currency not sure if you need the conversion to Long (seems like a mismatch there, please clarify. If you want a specific set of decimal points then it would be better to use decimal.Round )
Decimal value = default(decimal);
bool isValid = decimal.TryParse(txtWOrds.Text.Trim(), out value);
if (isValid)
{
//your code using output 'value'
}
Remove Convert.Int64 and just use Convert.ToDecimal (ideally you should use decimal.TryParse). Also, ensure that the input textbox contains the correct type (a decimal)
I found a workaround for this error, but am now really curious as to why this would be happening, was wondering if anyone else has had this error.
My function is as follows:
public void Blog_GetRating(int blogID, ref decimal rating, ref int voteCount)
{
// Sql statements
// Sql commands
if (DataReader.Read())
{
// this line throws a 'Input string was not in a correct format.' error.
rating = decimal.Parse(DataReader["Rating"].ToString());
// this works absolutly fine?!
decimal _rating = 0;
decimal.TryParse(DataReader["Rating"].ToString(), out _rating);
rating = _rating;
}
}
Anyone ever seen that before?
What's even weirder is if i type this:
rating = decimal.Parse("4.0");
that works fine, the 4.0 is what is coming out from my DataReader.
As I said previous, the TryParse method works fine so it's not stopping me from carrying, but now I'm really interested to see if anyone has an answer for it.
Looking forward to some replies!
Sean
EDIT - SOLVED
The decimal.Parse method was working fine, the second time the function was running (was in a loop), a post hadn't been rated so a null value was being returned by the data reader. Wrapping COALESCE round my calculation in SQL solved the problem fine. Hence why, as you said, the tryparse method wasn't throwing an exception, just keeping the default of 0 to _rating.
That doesn't look weird to me at all.
Decimal.Parse() is supposed to throw an exception for bad formats. Decimal.TryParse() will not throw that exception, but instead just return false. The kicker is that you're not checking the return value from Decimal.TryParse(). I'll give you real good odds that Decimal.TryParse() returns false for every input that causes an exception with Decimal.Parse(), and true everywhere else. And when Decimal.TryParse() returns false, the output argument is always just "0".
The one possible caveat is localization. If Decimal.Parse() is complaining about a seemingly normal input, you might check if the number format (current culture) used on your server uses a comma rather than a decimal to separate the coefficient from the mantissa. But given your "4.0" test worked fine, I doubt this is the problem.
Finally, when doing this conversion from data reader you should consider the source column type of the data reader. If might already be a decimal. Why convert it to a string only to convert it back?
You are saying this:
// this works absolutly fine?!
decimal _rating = 0;
decimal.TryParse(DataReader["Rating"].ToString(), out _rating);
But you didn't actually check the return value of TryParse. I would guess that your TryParse is actually failing (returning false), since decimal.Parse and decimal.TryParse use the same "rules" for parsing, given the overloads you're using.
I suspect that neither is working as you think. Both are probably failing, but TryParse won't throw.
The sql decimal column won't parse to a string that can convert to a Decimal, so tryparse will return false. Try something like this:
if (Convert.IsDBNull(reader["DecimalColumn"]))
{
decimalData = 0m;
}
else
{
decimalData = reader.GetDecimal(reader.GetOrdinal("DecimalColumn"));
}
I am facing same problem today.
Try this:
rating = decimal.Parse("4,0");
It will give you same error.
The reason behind this is the culture. In the French culture, 4.0 is represented as 4,0, and hence it throws an Exception.
decimal.TryParse is culture invariant method and hence it works fine you.
Change your TryParse to this and try again:
if (!decimal.TryParse(DataReader["Rating"].ToString(), out _rating))
{
throw new Exception("Input string was not in a correct format");
}
I bet this does throw...
The problem is with the convert of the txt box value, but why?
string strChar = strTest.Substring(0, Convert.ToInt16(txtBoxValue.Text));
Error is: Input string was not in a correct format.
Thanks all.
txtBoxValue.Text probably does not contain a valid int16.
A good way to avoid that error is to use .tryParse (.net 2.0 and up)
int subLength;
if(!int.TryParse(txtBoxValue.Text,out subLength)
subLength= 0;
string strChar = strTest.Substring(0, subLength);
This way, if txtBoxValue.Textdoes not contain a valid number then subLength will be set to 0;
One thing you may want to try is using TryParse
Int16 myInt16;
if(Int16.TryParse(myString, out myInt16)
{
string strChar = strTest.Substring(0, myInt16);
}
else
{
MessageBox.Show("Hey this isn't an Int16!");
}
A couple reasons the code could be faulty.
To really nail it down, put your short conversion on a new line, like this:
short val = Convert.ToInt16(txtBoxValue.Text);
string strChar = strTest.Substring(0, val);
Likely the value in txtBoxValue.Text is not a short (it might be too big, or have alpha characters in it). If it is valid and val gets assigned, then strTest might not have enough characters in it for substring to work, although this normally returns a different error. Also, the second parameter of substring might require an int (not sure, can't test right now) so you may need to actually convert to int32 instead of 16.
What is the value of txtBoxValue.Text during your tests?
ASP.NET offers several validation controls for checking user input. You should use something like a CompareValidator or RegularExpressionValiditor in your WebForm if you're expecting a specific type of input, eg, an Integer.