i would like to know is it possible to convert the string to int format.
eg: i need to store the the textbox value in to the variable state of type int.
so, is it possible to store it..?
My input value is string "Chennai",
if i pass this using int.Parse(textbox1.text) it shows input string is not in correct formate.
int state=textbox1.text;
Now we have a bit more information
It sounds like you don't want to parse a numeric string at all, which is the obvious interpretation of your original question.
If you want to map a string to a number, you'll need some sort of predefined map, e.g.
private static readonly Dictionary<string, int> StateNameMap = new
Dictionary<string, int>() {
{ "New Jersey", 1 },
{ "California", 2 },
...
};
Then you can use:
int state;
if (StateNameMap.TryGetValue(textbox1.Text, out state))
{
// Success
}
else
{
// Input was not a known state name. What do you want to do?
}
Original answer
You can certainly parse a string to an integer, using int.Parse
or int.TryParse
. For example:
// This will just throw an exception if the text is not a valid int
int state = int.Parse(textbox1.Text);
Or:
int state;
if (int.TryParse(textbox1.Text, out state))
{
// Success! Use state
}
else
{
// Invalid text - what do you want to do?
}
This is the common pattern for parsing in .NET, including DateTime
and other numeric types.
You should also consider what culture you expect the number to be in - less of a problem for integers than for non-integer values, but still something to consider.
See more on this question at Stackoverflow