This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I convert String to Int?
how can i change queryString value to an (int)
string str_id;
str_id = Request.QueryString["id"];
int id = (int)str_id;
Use Int32.TryParse Method to get int value safely:
int id;
string str_id = Request.QueryString["id"];
if(int.TryParse(str_id,out id))
{
//id now contains your int value
}
else
{
//str_id contained something else, i.e. not int
}
replace with this one
string str_id;
str_id = Request.QueryString["id"];
int id = Convert.ToInt32(str_id);
or simply and more efficient one
string str_id;
str_id = Request.QueryString["id"];
int id = int.Parse(str_id);
int id = Convert.ToInt32(str_id, CultureInfo.InvariantCulture);
There are several ways you can do that
string str_id = Request.QueryString["id"];
int id = 0;
//this prevent exception being thrown in case query string value is not a valid integer
Int32.TryParse(str_id, out id); //returns true if str_id is a valid integer and set the value of id to the value. False otherwise and id remains zero
Others
int id = Int32.Parse(str_id); //will throw exception if string is not valid integer
int id = Convert.ToInt32(str_id); //will throw exception if string is not valid integer
you have to use int.Parse(str_id)
Edit : don't trust user input
it's better to check if the input is a number or not before parsing , for this use int.TryParse
Related
I'm trying to convert a string to int with
Int32.TryParse(input, out int number);
and I want to keep the last integer value.
E.g.
If string input = "123" then int number = 123 and if string input = "" or null then int number should stay 123 till input had a new string value.
Have someone a idea?
Keep a copy of the previous value, and if the parse failed copy it back in:
var previousValue = 1;
if(!int.TryParse(input, out var number))
{
number = previousValue;
}
I have this code
string regex = Convert.ToString(itemDtlValid.Value);
string input = itemLst.Value;
string strRegex = "^[a-zA-Z0-9\\r\\t\\n ./?;:\"'`!##$%^&*()\\[\\]{}_+=|\\\\\\-~,]*$";
Regex re = new Regex(regex);
int comparer1 = regex.CompareTo(strRegex);
int comparer2 = String.CompareOrdinal(regex, strRegex);
data in the right column is the value that i have in db for itemDtlValid.Value:
itemDtlValid.Value i got from db which have same value as strRegex.
But then when i compare those two strings, comparer1 and comparer2 don't return 0.
Does anyone know why this happen? How to get comparer1 and comparer2 to return 0?
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:
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);
}
I need to convert a string in the database of patients to a int to create a new patient ID.
In the Hospital database, the patient ID is a STRING, not an integer. It is of the form p99. To create a new ID, I need to take out the p, convert to an integer, add 1, then put a 0 in if the value is less than 10, then add back the p.
I am using Microsoft visual studio and C#.
How would I go about this? Any help would be greatly appreciated!
You can use string.Substring Method and Int32.TryParse method.
String.Substring Method (Int32)
Retrieves a substring from this instance. The substring starts at a
specified character position.
Int32.TryParse Method (String, Int32)
Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the conversion
succeeded.
string patientId = "p99";
int id;
if (Int32.TryParse(patientId.Substring(1), out id))
{
patientId = string.Format("p{0}{1}", id < 10 ? "0" : string.Empty, id);
MessageBox.Show("Patient Id : " + patientId);
}
else
{
MessageBox.Show("Error while retrieving the patient id.");
}
You can use int.Parse() (MSDN) to convert a string to an integer.
You can write a simple routine to do this.
Assuming there is always a leading 'p' you can just do sID = sID.substring(1) to remove the first character.
Then you can use Int ID = Int16.Parse(sID) to convert to an Int (16-bit in this case). If you need 32-bit, use Int32.Parse
then ID++ or ID = ID+1 to increment by one.
Next, you need to convert back to a string with sID = ID.ToString()
Finally, do some string manipulation to test the length, add the leading '0' if length = 1, and the leading 'p'.