1

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

2 Answers2

0

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.

CodingBarfield
  • 3,392
  • 2
  • 27
  • 54
  • The MyDataTable column "DataType" is of System.Type, so it should only contain valid .Net types. So by following your idea I could use something like this? `if (row["DataType"].toString() == "String"){ try {Convert.ToString(Input);}catch...` ? –  Sep 26 '11 at 11:40
  • That depends a lot whether the user might supply "String" or "Object" while the content are doubles/numbers. Or if its always a valid .net datatype typed as the correct type. – CodingBarfield Sep 26 '11 at 11:49
0

Something like this might be helpful

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

        // Its not a type
    }
Apr
  • 26
  • 1