Read content as integer of empty XML element - c#

I encountered a problem while parsing XML in C# with XMLReader.
Here is an example:
string text = xNode.ReadElementContentAsString().Length > 0 ? xBonusesNode.ReadElementContentAsString() : null;
int nmb = xNode.ReadElementContentAsInt();
So, where I'm trying to get string value there is simple inline if statement to check if element has data or not.
How can I do something similar with integer? Or how to catch exception correctly and in best way, for this?

You can use int.TryParse like this:
int number;
bool result = Int32.TryParse(xNode.ReadElementContentAsString, out number);

string text = xNode.ReadElementContentAsString().Length > 0 ? xBonusesNode.ReadElementContentAsString() : null;
Int32.TryParse(text,out myInt);
Should work.
I'm not sure whether the xml library supports nullable types (int?) but the above should work anyway - basically I'm reading it as a string then trying to parse it. If TryParse fails myInt will remain as it was before (and tryParse returns 'false')

Related

Null value causing issue saving to the database

I am trying to convert a text box into a decimal when I try this method it says that inpurt string was not in correct format what is the best way around this.
_record.houseHoldArrearsAmount = Convert.ToDecimal(txtArrearsAmount.Text)
I persume it is because text is "" null and and 0.00 hence it falls over
The compiler run time is causing an exception
The input is blank if the user has not entered a value as of yet
If you know that the text is always going to be a number you can still use Convert but check that the string isn't empty first:
if (!string.IsNullOrWhitespace(txtArrearsAmount.Text))
{
_record.houseHoldArrearsAmount = Convert.ToDecimal(txtArrearsAmount.Text);
}
Obviously this won't update the houseHoldArrearsAmount if it's not a numeric value. What you do in this case depends on your business model. You might want to set it to 0 or you might want to leave it with the old value and report and error.
Alternatively, if the input could be any string, you can use Decimal.TryParse to convert the string to a number.
decimal result;
if (decimal.TryParse(txtArrearsAmount.Text, out result))
{
_record.houseHoldArrearsAmount = result;
}
You can use "TryParse" funtion.
decimal householdArrearsAmount = decimal.Zero;
decimal.TryParse(txtArrearsAmount.Text, out householdArrearsAmount);
_record.householdArrearsAmount = householdArrearsAmount;
You can't use the null coalescing operator (as your suggested in comments), as the string value of the textbox won't be null, it will be an empty string.
You could do the following:
_record.householdArrearsAmount =
(string.IsNullOrWhiteSpace(txtArrearsAmount.Text) ? 0 :
Convert.ToDecimal(txtArrearsAmount.Text));

Compare string null or empty in c#

In my table of MySQL Db I have the field Check.
The value memorized on the field Check it could be : null or -1.
When the value memorized on the field Check is null or -1 I need in return the xxx value. and I have tried :
string Check = sdr["Check"] == DBNull.Value || sdr["Check"] == "-1,00" ? "xxx" : sdr["Check"].ToString();
Without success because the output is always -1,00.
How to do resolve this?
Please help me, thank you so much in advance.
The problem is that you are comparing the wrong objects. The values returned from System.Data result sets are wrappers around the actual value. What you want are the typed versions. Basically, the check should look like this:
int checkIndex = sdr.GetOrdinal("Check");
string Check = sdr.IsDBNull(checkIndex) || (sdr.GetString(checkIndex) == "-1,00") ? "xxx" : sdr.GetString(checkIndex);
If you "Check" is actually a number, you may want to use the IntValue("Check") call, just to deal with globalization issues if your app is ever deployed where they use a "." instead of a "," for your decimal point.
See https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx for the full API.
If your MySQL database is not set to use the same locale formatting as your C# application, your assumptions about number formats could be incorrect. To make a more robust version of your check, I would recommend something like this:
int checkIndex = sdr.GetOrdinal("Check");
string Check = "xxx";
double checkValue = sdr.IsDBNull(checkIndex) ? -1 : Convert.ToDouble(sdr[checkIndex]);
if (checkValue != -1)
{
Check = checkValue.ToString(CultureInfo.CurrentCulture);
}
If the data type is decimal 10,2 you need Convert.ToDecimal the value :
string Check = (sdr["Check"] == DBNull.Value || Convert.ToDecimal(sdr["Check"]) == -1) ? "xxx" : sdr["Check"].ToString();
You can compare a string empty or null by below code
string str = Your string
if(String.IsNullOrEmpty(str))
{
if yes, it comes here
}
else
{
if not, it comes here
}
The String.IsNullOrEmpty() is a bool type.

Replace string value with '0' when string is empty

I'm taking a value from a textbox and converting it to decimal. But, the textbox value could be empty. So, how could I handle empty strings from the textbox?
Unfortunately I have around 50 textboxes to deal with, so answers like 'check for null with IF condition' won't help me. My code will look ugly if I use all those IF conditions.
I have this
Convert.ToDecimal(txtSample.Text)
To handle nulls, I did this
Convert.ToDecimal(txtSample.Text = string.IsNullOrEmpty(txtSample.Text) ? "0" : txtSample.Text)
But, the above code is displaying '0' in the textbox. User does not want to see '0'. Another solution is to take text box value into a variable and convert the variable like below.
string variable = txtSample.Text;
Convert.ToDecimal(variable = string.IsNullOrEmpty(variable) ? "0" : variable)
But again, I do not want to define around 50 variables. I am looking for some piece of code that handles null values during conversion without adding the extra line of code.
But, the above code is displaying '0' in the textbox. User does not want to see '0'.
This is because your statement is assigning the new value to txtSample.Text (when you do txtSample.Text = ...). Just remove the assignment:
Convert.ToDecimal(string.IsNullOrEmpty(txtSample.Text) ? "0" : txtSample.Text)
To make things easier if you have many text fields to handle, you can define an extension method :
public static string ZeroIfEmpty(this string s)
{
return string.IsNullOrEmpty(s) ? "0" : s;
}
And use it like this:
Convert.ToDecimal(txtSample.Text.ZeroIfEmpty())
You could make a function to keep from copying the code all over the place.
decimal GetTextboxValue(string textboxText)
{
return Convert.ToDecimal(string.IsNullOrEmpty(textboxText) ? "0" : textboxText);
}
and then use it like this:
GetTextboxValue(txtSample.Text);
You can create an extension method for the string as below
public static decimal ToDecimal(this string strValue)
{
decimal d;
if (decimal.TryParse(strValue, out d))
return d;
return 0;
}
Then you can just txtSample.Text.ToDecimal() in every place.

DataRow to bool casting

I have an xml file from which I read data in the unit test : [DataSource]
For the xml line : <DataBool>true</DataBool>, I try to read value by :
bool bData = (bool)TestContext.DataRow[4];
But it throws exception - invalid casting.What is the possible efficient solution?
If there's no schema associated with it, then it's probably just a string. If so, use bool.Parse or bool.TryParse to convert it from a string to a bool.
When you have int-tinyint value in DB :
int.Parse(dataRow["column_name"].ToString()) == 1 ? true : false

Convert string array value to int when empty string value is possible

I am having trouble converting a value in a string array to int since the value could possibly be null.
StreamReader reader = File.OpenText(filePath);
string currentLine = reader.ReadLine();
string[] splitLine = currentLine.Split(new char[] { '|' });
object.intValue = Convert.ToInt32(splitLine[10]);
This works great except for when splitLine[10] is null.
An error is thrown: `System.FormatException: Input string was not in a correct format.
Can someone provide me with some advice as to what the best approach in handling this would be?
Don't use convert, it is better to use
int.TryParse()
e.g.
int val = 0;
if (int.TryParse(splitLine[10], out val))
obj.intValue = val;
You can use a TryParse method:
int value;
if(Int32.TryParse(splitLine[10], out value))
{
object.intValue = value;
}
else
{
// Do something with incorrect parse value
}
if (splitLine[10] != null)
object.intValue = Convert.ToInt32(splitLine[10]);
else
//do something else, if you want
You might also want to check that splitLine.Length > 10 before getting splitLine[10].
If you're reading something like a CSV file, and there's a chance it could be somewhat complicated, such as reading multiple values, it probably will make sense for you to use a connection string or other library-sorta-thing to read your file. Get example connection strings from http://www.connectionstrings.com/textfile, using Delimited(|) to specify your delimiter, and then use them like using (var conn = new OleDbConnection(connectionString)). See the section in http://www.codeproject.com/Articles/27802/Using-OleDb-to-Import-Text-Files-tab-CSV-custom about using the Jet engine.
I would go with
object.intValue = int.Parse(splitLine[10] ?? "<int value you want>");
if you're looking for the least code to write, try
object.intValue = Convert.ToInt32(splitLine[10] ?? "0");
If you want to preserve the meaning of the null in splitLine[10], then you will need to change the type of intValue to be of type Nullable<Int32>, and then you can assign null to it. That's going to represent a lot more work, but that is the best way to use null values with value types like integers, regardless of how you get them.

Categories