Reputation: 17293
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.
//}
}
}
Upvotes: 5
Views: 17101
Reputation: 196
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();
Upvotes: 0
Reputation: 35399
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 .... */
Upvotes: 13