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.
Related
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));
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.
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')
I'm saving a numeric value into a datatable cell (no datatype for the cell has been explicitly declared), then later retrieving that data and trying to format it into a string. Problem is that nothing I've tried will properly format the string.
50000 --> 50,000
I've tried (where r is the row in a loop):
String.Format("{0:0,0}", r["columnName"])
r["columnName"].ToString("n0")
And several variations without any luck. Most of the time I just get the number without the comma.
String.Format("{0:0,0}",int.Parse(r["columnName"].ToString()))
Probably not the most elegant solution, but you could just iterate backwards from the tail-end of the string (or from the decimal point) adding a comma every three characters until you run out.
It might be helpful to have more context for what you're trying to do, but here is an example of getting a value out of a DataTable and then formatting it as desired.
DataTable dt = new DataTable();
dt.Columns.Add( "cellName", typeof( double ) );
dt.Rows.Add( 123.45 );
string val = ( (double)dt.Rows[0]["cellName"] ).ToString( "N" ); // val = "123.45"
I'm explicitly casting the value back to a double before calling ToString. You could also call string.Format on that value instead of ToString and it should work just as well.
EDIT: If you're storing the value as a string and then want to format it, use this:
string val = ( double.Parse( dt.Rows[0]["cellName"] ) ).ToString( "N" );
This does assume that the value is parsable though (i.e. isn't null).
The problem with these methods is that depending on the structure of the underlying table that field may be null. If you try to cast a null value held as an object (in the DataTable) to string,integer, decimal, or what have you... your app will blow up 100% of the time. Unless your DataSet is a strongly typed data set you will always want to do this error checking. As a matter of fact, writing a small data reading class to read string, decimals, date times, integers, whatever... is a must in any Data access operations having to do with Database....
So here is more error proof approach which idealy should be wrapped in a helper method as shown here:
public static string GetFormatedDecimalString(DataRow row, string columnName, string format)
{
string ColumnNameStringValue = String.Empty;
decimal ColumnNameValue = Decimal.Zero;
if( row[columnName) == DBNull.Value )
{
ColumnNameValue = Decimal.Zero;
}
else
{
ColumnNameStringValue = row[columnName].ToString();
if( ! Decimal.TryParse(ColumnNameStringValue, out ColumnNameValue )
{
ColumnNameValue = Decimal.Zero;
}
// if the if statement evaluated to false the ColumnNameValue will have the right
// number you are looking for.
}
return ColumnNameValue.ToString(format);
}
passing "N" or "{0:0,0}" as the format string will work just fine.
I have a very simple C# question: aren't the following statements equal when dealing with an empty string?
s ?? "default";
or
(!string.IsNullOrEmpty(s)) ? s : "default";
I think: since string.Empty!=null, the coalescence operator may set the result of the first statement to an empty value when what I really want is the second. Since string is someway special (== and != are overloaded to value-compare) I just wanted to ask to C# experts to make sure.
Thank you.
Yes, you're right - they're not the same, and in the way that you specified.
If you're not happy with the first form, you could write an extension of:
public static string DefaultIfNullOrEmpty(this string x, string defaultValue)
{
return string.IsNullOrEmpty(x) ? defaultValue : x;
}
then you can just write:
s.DefaultIfNullOrEmpty("default")
in your main code.