Sign in to follow this  
Winegums

Combo Box Data reading in C#

Recommended Posts

Hi, Im trying to read the data from a c# combo box (which users can type in) and turn it into a number. Ignoring the possability of non numeric input (though any pointers on data validation would be great too), how do i read in the string from the combo box and convert it to an integer?

Share this post


Link to post
Share on other sites
With a ComboBox named myComboBox:


int number;
if (Int32.TryParse(myComboBox.Text, out number) && number >= minValue && number <= maxValue)
{
// Do whatever with 'number' here.
}
else
{
// ComboBox text doesn't currently represent a valid number.
}

TryParse returns false if either the string passed in was a null reference (which should never happen in this context) or if the string does not represent a valid number (correctly formatted and within the range of the datatype). The else block, therefore, will be executed if the number entered is either invalid, or not within the range minValue to maxValue (remove these extra conditionals as appropriate).

You may also use this with unsigned int if you don't wish to accept negative numbers as input: declare 'number' as a uint instead, and use UInt32.TryParse in the same way.

[Edited by - PaulRTC on June 6, 2007 6:28:29 AM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this