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);
}
Related
This question already has answers here:
Test if string is a guid without throwing exceptions?
(19 answers)
Closed 5 years ago.
I have string type value like "e2ddfa02610e48e983824b23ac955632". I need to add - in this code means convert in Guid.
EntityKey = "e2ddfa02610e48e983824b23ac955632";
Id = (Guid)paymentRecord.EntityKey;
Just a simple creation:
String source = "e2ddfa02610e48e983824b23ac955632";
Guid result = new Guid(source);
You could do :
Guid guid;
if (Guid.TryParse("e2ddfa02610e48e983824b23ac955632", out guid))
{
// succeed...
}
else
{
// failed...
}
Edit : Like #Silvermind said, if you know the format of the input, you can use Guid.TryParseExact with the "N" format in your case.
For parsing the string to a Guid. You can do this:
var guid= "e2ddfa02610e48e983824b23ac955632";
var result= Guid.ParseExact(guid,"N")
Or if you prefer to have it in a try parse. You can also do this:
Guid result;
if(Guid.TryParseExact(guid,"N",out result))
{
//Do something
}
The "N" is a format which indicates that the string will be format with 32 digits without "-"
Reference:
Guid.TryParseExact Method (String, String, Guid)
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.
This question already has answers here:
Convert string to decimal, keeping fractions
(12 answers)
Closed 8 years ago.
String ItemName=txtItemName.Text.ToString();
String ItemSpecification=txtItemSpecification.Text.ToString ();
String Category=cmbCategory.SelectedIndex .ToString();
String UnitOfMeasurement=cmbUnitOfMeasurement .SelectedIndex .ToString ();
Decimal Reorderlevel = txtReorderLevel.Text.();
Decimal LifeOfSpan=0;
String NeedApproval=rblNeedApprovalOrNotdx.SelectedItem.Value.ToString();
String Description=MemoDescription.Text.ToString ();
For string I can get a value using ToString. How can I get it for decimal?
Use Convert.ToDecimal() method to convert string to decimal.
The below code prints the value as 1200.00.
var convertDecimal = Convert.ToDecimal("1200.00");
Just in case it's cultural issues, try this version which shouldn't depend on your locale at all:
decimal d = decimal.Parse("1200.00", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString(CultureInfo.InvariantCulture));
I have always preferred using the Double.TryParse methods because it is going to spit back success or failure to convert without having to worry about exceptions.
string value;
double number;
value = Double.MinValue.ToString();
if (Double.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("{0} is outside the range of a Double.",
value);
Use Decimal.TryParse(), like this:
decimal Reorderlevel;
if (Decimal.TryParse(UnitOfMeasurement, out Reorderlevel))
{
// Conversion from string to decimal succeeded
}
else
{
// Conversion failed
}
Note: TryParse() does not thrown an exception if the attempted cast from string to decimal fails, but rather returns false when it fails and true when it succeeds.
UPDATE:
If you prefer to use a nullable decimal, then do this:
decimal tempValue;
decimal? Reorderlevel = Decimal.TryParse(UnitOfMeasurement, out tmpvalue) ?
tmpvalue : (decimal?)null;
Then you can check if Reorderlevel has a value before using it, like this:
if(Reorderlevel.HasValue)
{
// Do something with reorder level value here
}
Use Convert.ToDecimal() or Decimal.TryParse()
You can use the method Convert.ToDecimal() from the System namespace.
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?
I am using C# and I want to convert a string to int to verify name. For example ** or 12 is not a name. I just want to convert the string into ASCII values and then will verify the name. How do I do that?
Converting back and forth is simple:
int i = int.Parse("42");
string s = i.ToString();
If you do not know that the input string is valid, use the int.TryParse() method.
From what I understand, you want to verify that a given string represents a valid name? I'd say you should probably provide more details as to what constitutes a valid name to you, but I can take a stab at it. You could always iterate over all the characters in the string, making sure they're letters or white space:
public bool IsValidName(string theString)
{
for (int i = 0; i < theString.Length - 1; i++)
{
if (!char.IsLetter(theString[i]) && !char.IsWhiteSpace(theString[i]))
{
return false;
}
}
return true;
}
Of course names can have other legitimate characters, such as apostrophe ' so you'd have to customize this a bit, but it's a starting point from what I understand your question truly is. (Evidently, not all white space characters would qualify as acceptable either.)
There multiple ways to convert:
try
{
string num = "100";
int value;
bool isSuccess = int.TryParse(num, out value);
if(isSuccess)
{
value = value + 1;
Console.WriteLine("Value is " + value);
}
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
It's not clear to me what you're trying to do, but you can get the ASCII codes for a string with this code:
System.Text.Encoding.ASCII.GetBytes(str)