Reputation: 2889
I want to read from my response data reader object the column name and type, because i need it to instantiate some objects. I came out with this :
using (db.sqlConnection) {
db.sqlConnection.Open();
using (var cmd = new SqlCommand("areaGetStreetTypes", db.sqlConnection)) {
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.KeyInfo)) {
DataTable dt = dr.GetSchemaTable();
foreach (DataRow myField in dt.Rows) {
foreach (DataColumn coloana in dt.Columns) {
string c1 = coloana.ColumnName; //column name ???
string c2 = coloana.GetType().ToString(); //column type ??
Console.WriteLine(c1 + " " + c2);
}
}
}
}
}
but is not working. For each column returns i want to print (for starter) something like :
id_someID int32
name string
surname string
ssn string
what is wrong in my code?
Upvotes: 0
Views: 4365
Reputation: 20775
No need to call GetSchemaTable to get datatype for each column because Reader already have all these details
SqlCommand cmd = new SqlCommand(strSql, sqlConn);
SqlDataReader sdr;
sdr = cmd.ExecuteReader();
for (int i = 0; i < sdr.FieldCount; i++)
{
string dataTypeName = sdr.GetDataTypeName(i); // Gets the type of the specified column in SQL Server data type format
string FullName = sdr.GetFieldType(i).FullName; // Gets the type of the specified column in .NET data type format
string specificfullname = sdr.GetProviderSpecificFieldType(i).FullName; //Gets the type of the specified column in provider-specific format
//Now print the values
}
Upvotes: 4
Reputation: 35746
I think you actually want somthing like
DataTable dt = dr.GetSchemaTable();
foreach (DataRow myField in dt.Rows)
{
var name = myField["ColumnName"];
var type = myField["DataTypeName"];
Console.WriteLine("{0} {1}", name, type);
}
Upvotes: 3
Reputation: 100368
Use DataColumn.DataType
property and CommandBehavior.SchemaOnly
enum member.
Upvotes: 1