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?
You can get the ordinal of the column by using the GetOrdinal
method, so your call could be:
read.GetValue(read.GetOrdinal("ColumnID"));
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With