sebastian.roibu
sebastian.roibu

Reputation: 2889

Load data from datareader

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

Answers (3)

Romil Kumar Jain
Romil Kumar Jain

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

Jodrell
Jodrell

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

abatishchev
abatishchev

Reputation: 100368

Use DataColumn.DataType property and CommandBehavior.SchemaOnly enum member.

Upvotes: 1

Related Questions