Combo Box Data reading in C#

Started by
0 comments, last by PaulRTC 16 years, 10 months ago
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?
Advertisement
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]

This topic is closed to new replies.

Advertisement