5

I'm not sure what exactly I'm doing wrong, can someone correct it please? I need to determine the type of a retrieved column from a SQL Server database using C#.

Say, I have this:

SqlConnection cn = new SqlConnection("Sql Connection String");
SqlCommand cmd = new SqlCommand("SELECT * FROM [TableName]", cn);
SqlDataReader rdr = cmd.ExecuteReader();

while (rdr.Read())
{
    for (int c = 0; c < rdr.VisibleFieldCount; c++)
    {
        System.Type type = rdr.GetFieldType(c);

        //So can I do this? (Pseudo-code)
        //switch(type)
        //{
        //case string:
        //case int:
        //case DateTime:
        //etc.
        //}
    }
}
6
  • 1
    Is there a reason why you don't use a context? Why don't you use LinqToSql or Entity Framework? Commented Mar 15, 2012 at 1:14
  • Yes. I don't know what those are. Do you have a link I can check? Commented Mar 15, 2012 at 1:19
  • Check out this related question: stackoverflow.com/questions/258840/… Commented Mar 15, 2012 at 2:34
  • It seems to me you should know what your database table's schema is and thus youshould know what those types are..... Commented Mar 15, 2012 at 6:05
  • It would be a lot easier to use something like Entity Framework - it will handle a lot of those issues for you, and shield you from the boring details of data access... Commented Mar 15, 2012 at 6:07

2 Answers 2

13

You can do the following:

/* ... code .... */

System.Type type = rdr.GetFieldType(c);

switch (Type.GetTypeCode(type))
{
    case TypeCode.DateTime:
        break;
    case TypeCode.String:
        break;
    default: break;
}

/* ... code .... */
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, dude. It works, except two cases: when I have a UNIQUEIDENTIFIER and BINARY data types. Both are returned as Object, when they should be Guid and Byte[]. Any idea how to handle that?
@ahmd0: if (type == typeof(System.Guid)) for instance.
Correct ... you could do that in the default block of the switch statement ...
0

Here is some code that worked for me:

SqlCommand ubCommand = new SqlCommand(sqltext);
ubCommand.Connection = ubConnection;
SqlDataReader ubReader = null;
ubReader = ubCommand.ExecuteReader();
ubReader.Read();
schednum = ToInt32(ubReader["ScheduleNum"].ToString());
int fieldNum;
lbl_schedule.Text = $"Schedule {schednum}";
for (i = 0; i < num_fields; i++)
{
 fieldNum = ubReader.GetOrdinal(fields[i]);
 values[i] = ubReader[fieldNum].ToString();
 types[i] = ubReader.GetFieldType(fieldNum);
 // Check types[i].Name for the results, like "String" or "Decimal"
}
ubReader.Close();
ubConnection.Close();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.