Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlDataReader Get Value By Column Name (Not Ordinal Number)

Using the methods of the SqlDataReader, I can get the value of a column by passing in it's ordinal, such as the value of the first column if I pass in read.GetValue(0), or the second column if I pass in read.GetValue(1).

In looking at the methods, I don't see an option to get the value of a column by passing in the name of a column, such as ColumnID. In my mythical example, I would want to pass in read.GetValueofColumn("ColumnID") and read the value in the column (note that the method GetValueofColumn doesn't exist so far as I can tell from the method list).

Am I missing the method to do this, or a way to do this?

like image 419
user9927 Avatar asked Feb 04 '15 15:02

user9927


3 Answers

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

read.GetValue(read.GetOrdinal("ColumnID"));
like image 134
MatthewG Avatar answered Oct 19 '22 02:10

MatthewG


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)

like image 21
Emanuele Greco Avatar answered Oct 19 '22 02:10

Emanuele Greco


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);
        }

    }
}
like image 13
Kirby L. Wallace Avatar answered Oct 19 '22 03:10

Kirby L. Wallace