Converting String to Integer

Use the Convert.ToInt32(string) method to convert a string to integer.

int startingMileage;

startingMileage = Convert.ToInt32(txtStartingMileage.Text);

This however doesn’t confirm if textbox is an integer or text so it’s not effective as is.

This entry was posted in Csharp and tagged . Bookmark the permalink.

2 Responses to Converting String to Integer

  1. cabbo says:

    you could just limit the input in the textbox using events. So for the textbox, have a KeyPress event that checks if the input is a number (or . or – or , or whatever) and handle it if so or deny it if not.

    did a quick google search and found this snippit at http://www.syncfusion.com/faq/windowsforms/faq_c94c.aspx#q830q

    public class NumbersOnlyTextBox : TextBox
    {
    public NumbersOnlyTextBox()
    {
    this.KeyPress += new KeyPressEventHandler(HandleKeyPress);
    }

    private void HandleKeyPress(object sender, KeyPressEventArgs e)
    {
    if(!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
    e.Handled = true;
    }
    }

  2. Hayami says:

    ok nerd