SqlDataReader Get value by column name (not default)

Using the methods of the SqlDataReader method , I can get the column value by passing it a serial number, for example, the value of the first column if I go through read.GetValue(0), or the second column if I go through read.GetValue(1).

When looking at methods, I don’t see the possibility of getting the column value by passing the column name, for example ColumnID. In my mythical example, I would like to go through read.GetValueofColumn("ColumnID")and read the value in the column ( note that the method GetValueofColumndoes not exist, as far as I can tell from the list of methods ).

Am I missing a method for this or a way to do this?

+4
source share
3

GetOrdinal, :

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

Datareader () ( ) . ,

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

(, reader Datareader)

+11

Late answer, but ... It always worked for me, and I think it is closer to what the 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);
        }

    }
}
+2
source

All Articles