Search code examples
c#typesuser-inputgetschematable

Check if Datatype from schematable and user data match


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


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
        }