Question

I'm having a little problem with checking user inputs. I want to check if an input is of a "given" datatype. The problem is in the "given" as you might have guessed :-)

I get an SQLschematable via a Datareader. The database can be exchanged, for the program should be able to work with any foreign database. Therefore I don't know anything else about it. The schematable lists all columns from the database table. It contains a column "DataType" where the .Net datatype corresponding to the databases column datatypes are listed.

The user can specify a data input for each column in a datagridview. That is: the user is given the schematable and an editable extra column.

Now I want to check if the given user input matches the .Net datatype. Normaly I would check this by using something like

Input is String

or

String test = Input as String;
if (test = null) ....

but the problem is in creating the Datatype (i.e. the String)

if I do something like this:

foreach (DataRow row in MyDataTable.Rows){
    System.Type t = (System.Type) row["DataType"];
    if (! ( ((Object) row["Input"]) is t ) ){
        MessageBox.Show("Error");
    }
}

than t is not recognized as a datatype and the "is" command is not used properly.

I also tried the more direct aproach with

foreach (DataRow row in MyDataTable.Rows){
  if ( ! (row[Input] is ((System.Type) row["DataType"] ))) ...

and many similar lines, but it seems this "is" command only works with types that are directly referenced form System.Type, like in "is String".

How could one solve this?

thanks in advance, Peter

Was it helpful?

Solution

Something like this might be helpful

try
    {
        object o = Convert.ChangeType(row["Input"], Type.GetType(row["DataType"]));
    }
    catch (Exception ex)
    {

        // Its not a type
    }

OTHER TIPS

This depends a bit whether the actual row-columns have a valid datatype (from the database) or all columns contain string types (as a generic user input type)

In practice I would go for a list of

Try
  Convert.ToX
Catch
 'oops not type X
End try

For all expected datatypes with 'string' as a catch all. Ordered a bit from Integer to float etc so the datatypes are a bit restricted with some Money and Date types added for completeness.

Sure this is a dirty list but there isn't any other way that I know of.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top