SqlDataReader Get Value By Column Name (Not Ordinal Number)

Datareader has numeric (position based) method, and a textual (field name based) one. So, with field name, you can get the value like

object value = reader["some field name"];

(assuming that reader is a datareader)


Late answer, but... This has always worked for me, and I think it is closer to what OP is trying to achieve:

using (SqlCommand cmd = new SqlCommand(cmdString, cn))
using (SqlDataReader rs = cmd.ExecuteReader()) {

    if (rs.HasRows) {

        while (rs.Read()) {

            Meeting_DiscussionItems_MX di = new Meeting_DiscussionItems_MX();

            di._Discussion_Item_MX_ID   = (int) rs["Discussion_Item_MX_ID"];
            di._Meeting_ID              = (int) rs["Meeting_ID"];
            di._Discussion_Item_Name    = (string) rs["Discussion_Item_Name"];
            di._Display_Order           = (string) rs["Display_Order"];
            di._Status                  = (string) rs["Status"];
            di._Discussion_Items        = (string) rs["Discussion_Items"];
            di._ETOPS_Items             = (string) rs["ETOPS_Items"];
            di._Followup                = (string) rs["Followup"];
            di._Pinned                  = (string) rs["Pinned"];
            di._Active                  = (string) rs["Active"];

            _Meeting_DiscussionItems_MX.Add(di);
        }

    }
}

You can get the ordinal of the column by using the GetOrdinal method, so your call could be:

read.GetValue(read.GetOrdinal("ColumnID"));

For convenience you can add some helpers like this:

public static string GetString(this SqlDataReader reader, string name) {
    return GetFieldValue<String>(reader, name, (string)null);
}

public static T GetFieldValue<T>(this SqlDataReader reader, string fieldName, T defaultvalue = default(T)) {
    try {
        var value = reader[fieldName];
        if (value == DBNull.Value || value == null)
            return defaultvalue;
        return (T)value;
    } catch (Exception e) {
        //SimpleLog.Error("Error reading databasefield " + fieldName + "| ", e);
    }
    return defaultvalue;
}

As you can see it is the reader that allows to use fieldnames but it returns an object that needs to be casted to the right datatype. The extension takes care of both and adds a defaultvalue for when the field is null.