You call a number of
Convert.To*
methods having no guarantee that the string passed as an argument really can be parsed as a value of required type. If it doesn't, you throw an exception, which you can handle and recover. But this is not a right way. Even the class name
Convert
is somewhat misleading. You need to understand what really happens, and this is nothing but
parsing. You should better use the
TryParse
method for each expected type. For example, for
int
, you can use
bool int.TryParse(string, out int)
, and so on. If such method returns false, you know that the input string is not in an expected format, and the valid value is not returned via the second
out
parameter.
Moreover, your code sample strongly suggests that you tend to work with strings representing data, instead of data itself. You should better avoid it, reserving strings mostly for output purposes, such as showing on screen. For example, for the type
decimal
and integer types, you can use the control
System.Windows.Forms.NumericUpDown
(in can also be used indirectly for floating-point type, if you need input with fixed precision, which is usually the case):
NumericUpDown Class (System.Windows.Forms)[
^].
Also, you can use
System.Windows.Forms.DataGridView
where you can use strongly-typed cell data. Some types of the cell derived from
System.Windows.Forms.DataGridViewCell
are already available for some commonly used data types, some you can develop yourself. Please see:
DataGridView Class (System.Windows.Forms)[
^],
DataGridViewCell Class (System.Windows.Forms)[
^],
DataGridViewCell.Value Property (System.Windows.Forms)[
^],
DataGridViewCell.ValueType Property (System.Windows.Forms)[
^].
And so on… It were just some of the idea, something to think about.
—SA