ASP.net Converting inputbox string to integer? - c#

I have been trying for ages to convert a string taken from an input box in my asp form and converting it to an integer.
This integer variable will then be used for a database operation I have planned.
Here is what I have tryed:
string mytxtCHI = txtID.Text;
int #CHI = Convert.ToInt16(mytxtCHI);
Error:
System.FormatException
{"Input string was not in a correct format."}
Things I have tried:
- string mytxtCHI = txtID.Text;
int myNewID=(Int32.Parse(txtID.Text));
Thankyou for your time :)

Your way is correct, but what you should do to avoid errors
int myNewID = 0;
if(int.TryParse(txtID.Text, out myNewID))
{
//your code here
}
else
{
//your error handling here
}

You should use tryparse:
string mytxtCHI = txtID.Text;
int number;
bool result = Int32.TryParse(mytxtCHI , out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", mytxtCHI , number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", mytxtCHI );
}

Put a breakpoint on the line in Visual Studio. In debug mode, run to the breakpoint, and hover over txtID.Text to see what's in it.
When in the page lifecycle are you checking this value? Check it after Page Init. Check HttpRequest.Form to see what came down the wire.

You should use Int.TryParse, and handle the case when the value isn't a valid integer.
string mytxtCHI = txtId.Text;
int val;
if (!int.TryParse(mytxtCHI, out val))
{
// error here, value was not a valid integer.
}
// here, val contains the value, expressed as an integer.

Use watch window or System.Diagnostics.Debug.WriteLine(mytxtCHI) to check what's the value you are passing, is it blank?

Related

Assign string value for decimal value

_item = new OutTYonetimOzet();
_item.Banka = Convert.ToDecimal(" ");
liste.Add(_item);
There is a list called liste. In List item Banka named element is decimal value. I want to show the empty string when I show it on the screen. But this code is getting an error that can not be cast. What is the problem.
Error message is:
Input string was not in a correct format.
There's no such thing as a "blank decimal". decimal cannot have a value that is "blank" - it always has a numeric value. Convert.ToDecimal(" ") is nonsensical - there is nothing it can return that makes sense.
You could try using a Nullable<decimal> (aka decimal?) perhaps; i.e.
public decimal? Banka {get;set;}
and
_item.Banka = null;
You can also use the decimal.TryParse instead of Convert. With this technique you can check if the string is valid.
_item = new OutTYonetimOzet();
decimal val = decimal.MinValue;
if (decimal.TryParse(" ", out val))
{
_item.Banka = val;
}
else
{
//your default goes here
_item.Banka = 0;
}
liste.Add(_item);
and as Mark suggested I would use Nullable<decimal> and use null as default value.

how to handle format exception for different textboxes with a custom message

I am inserting data in my database with a sqlcommand and parameters.All that is in my try {} part..after that I have a catch{} that gets exceptions.
My problem is that I have a date text boxes,and I have a integer texboxes.
How can I have for my date field
`catch{FormatException)
{
messagebox.show("Your date field must be dd/mm/yyy");
}
and how can I have for my integer field
`catch{FormatException)
{
messagebox.show("That field must be integer");
}
How can I separate those two format exceptions?
For date input rather than using textbox, use DatePicker. It will exclude the need to check for the format.
<DatePicker name="datePicker"></DatePicker>
And to get the value picked by date in behind code,
datePicker.SelectedDate
Now you only have to check for integer.
int parsedValue;
if(int.TryParse(convertToInt, out parsedValue)){
// All Ok
}
else {
messageError = "That field must be integer";
// Display error contained witin messageError
}
No need to put try catch as well.
Both FormatExceptions give different values for the exc.Message (where exc is the exception variable). For an int, it's "Input string was not in a correct format." and for a DateTime it's "String was not recognized as a valid DateTime.".
So you could just use a single try-catch and check for this string at the end, but that could create problems later on (code becomes hard to maintain). It's better to use separate try-catch blocks.
string messageError = null;
string convertTodate = "34/";
string convertToInt = "3.5";
try
{
int newInt = Convert.ToInt32(convertToInt);
}
catch(FormatException)
{
messageError = "That field must be integer";
}
try
{
DateTime newDate = Convert.ToDateTime(convertTodate);
}
catch(FormatException)
{
messageError = "Your date field must be dd/mm/yyy";
}
if(string.IsNullOrEmpty(messageError))
{
// All Ok
}
else
{
// Display error contained witin messageError
}

System.FormatException is unhandled by user code

I am sending my poolid in hdnfield when am converting it to show me error . poolid is int32 datatype
if (ddlStaticPoolName.Visible)
{
objUserEntity.POOLNAME = Convert.ToString(ddlStaticPoolName.SelectedItem.Text);
objUserEntity.POOlID = Convert.ToInt32(ddlStaticPoolName.SelectedValue);
}
else if (lblDynamicPoolName.Visible)
{
objUserEntity.POOLNAME = Convert.ToString(lblDynamicPoolName.Text);
objUserEntity.POOlID =Convert.ToInt32(hdnDynamicPoolID.Value);
}
else
{
objUserEntity.POOLNAME = "";
objUserEntity.POOlID = 0;
}
If the string Contains numerical characters But its not Whole Number (ex: double , decimal).
objUserEntity.POOlID = Convert.ToInt32(Convert.ToDouble(ddlStaticPoolName.SelectedValue));
If the string contains double Number it Cant be directly converted to Int. If this not Solve your problem you must give an Example of ddlStaticPoolName.SelectedValue.
If the string Contains Non numerical characters. Then you should use TryParse.
int num;
Int32.TryParse(ddlStaticPoolName.SelectedValue, out num);
objUserEntity.POOlID = num;
If the string contains invalid number. TryParse will set the value of num to 0. otherwise to the value Converted from string.
If you try this solutions one of them must solve your problem. But Try First solution then go To the next solution.

convert string value to int [duplicate]

This question already has answers here:
Not able to cast string to int. Error msg: Input string was not in a correct format
(6 answers)
Closed 9 years ago.
if (!IsPostBack)
{
string EnquiryID = (Session["Enq_ID"].ToString());
if (EnquiryID != null)
{
int Enquiry = Convert.ToInt32(EnquiryID);
hotelOBJ.FillbyQueryEnquiry1(Enquiry, txtClientph, txtClientAddress );
}
}
there is my code my session is not convert into integer the error is
"Input string was not in a correct format. "
The error says that there might be some characters that can't be converted to Integer in any case like 1234ab contains characters ab which can't be converted to Integer.
What you can do is:
bool result = Int32.TryParse(Session["Enq_ID"].ToString(), out number);
if (result)
{
hotelOBJ.FillbyQueryEnquiry1(number, txtClientph, txtClientAddress );
}
else
{
Console.WriteLine("Attempted conversion of '{0}' failed.",
Session["Enq_ID"].ToString());
}
I think the string that you try to convert to int is empty or it contains characters that is not digits (basically your string does not represent an integer value in a string form). That's why you get that error message.
So at least you have to replace your
if (EnquiryID != null)
with
if(!string.IsNullOrWhiteSpace(EnquiryID))
That's how you will know what if you try to convert variable it at least have something to convert.
And or use Int32.TryParse() function to test (and convert to integer) if the string that you try to convert is an integer.
Use Int32.Parse(). Beware FormatException when parsing, its good to use TryParse first or wrap TryParse in an extension method. Also change your if statement. The way you have it now can result in NullReferenceException if your query string parameter is missing.
if (!IsPostBack)
{
if (Session["Enq_ID"] != null)
{
string EnquiryID = Session["Enq_ID"].ToString();
if (EnquiryID.IsValidInt32())
{
int Enquiry =Int32.Parse(EnquiryID);
hotelOBJ.FillbyQueryEnquiry1(Enquiry, txtClientph, txtClientAddress );
}
}
}
Extension method...
public static bool IsValidInt32(this string value)
{
int result;
return int.TryParse(value, out result);
}

how to do this conversion?

string mvi = Moneys.GetValue(8) as string;
if (mvi == null)
// I am getting exception Here if its null?
money.Currency= Convert.ToDecimal("");
else
// Currency is Decimal
money.Currency= Convert.ToDecimal(mvi);
// I am getting exception Here if its null?
money.Currency= Convert.ToDecimal("");
Can anybody tell me how to do this?
Empty string is not convertible to decimal. You could perform a check like this
if (string.IsNullOrEmpty(mvi))
{
money.Currency = 0M;
}
else
{
decimal temp = 0M;
if (decimal.TryParse(mvi, out temp))
{
money.Currency = temp;
}
else
{
// you have an invalid input, handle
}
}
Here's my version of Anthony Pegram's answer:
string mvi = Moneys.GetValue(8) as string;
money.Currency = 0M;
if (!String.IsNullOrEmpty(mvi))
if (!Decimal.TryParse(mvi, out money.Currency))
throw new FormatException("mvi");
On the whole, it looks quite a bit like the one Alex made, only it treats empty as zero and shows more error-handling.
You can use TryParse instead of Convert.ToDecimal():
decimal theValue;
string mvi = Moneys.GetValue(8) as string;
Decimal.TryParse( mvi, out theValue );
alternatively, you can use the null coallescing operator to handle nulls preemtively:
var theValue = Convert.ToDecimal( mvi ?? "0" );
In both cases, however, you have to decide what to do if the value coming in is not a valid decimal.
http://msdn.microsoft.com/en-us/library/hf9z3s65.aspx
I think you want Convert.ToDecimal("0.0"); otherwise you get a EDIT: ArgumentNullException

Categories