Skip to content
Advertisement

Get the ID of the column being read in SqlDataReader

I’m currently reading from an ancient stored procedure.

I know you can get the FieldType and FieldCount to get type/size of the columns but is there a way to get the actual ID of the column to read from the reader?

The ID I’m referring to is this:

SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
    SomeObject obj = new SomeObject{
        SomeProperty = reader["ID"]
    };
}

I don’t want to bind it arbitrarily to some var but to obtain the actual column name it’s returning in the results set if possible?

Advertisement

Answer

You could do something like that and gather all name that contains in reader:

var columns = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList();
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement