DataReader.GetString() via columnname

You’re looking for the GetOrdinal method: this._MyField1 = reader.GetString(dr.GetOrdinal(“field1”)); this._Myfield2 = reader.GetInt16(dr.GetOrdinal(“field2”)); I generally cache the ordinals in an anonymous type for performance and readability: // … using (IDataReader dr = cmd.ExecuteReader()) { var ordinals = new { Foo = dr.GetOrdinal(“Foo”), Bar = dr.GetOrdinal(“Bar”) }; while (dr.Read()) { DoSomething(dr.GetString(ordinals.Foo), dr.GetInt16(ordinals.Bar)); } } // …

Multiples Table in DataReader

Try this because this will close connection ,data reader and command once task get over , so that this will not give datareader close exception Also do check like this if(reader.NextResult()) to check there is next result, using (SqlConnection connection = new SqlConnection(“connection string here”)) { using (SqlCommand command = new SqlCommand (“SELECT Column1 FROM … Read more

Is datareader quicker than dataset when populating a datatable?

The DataAdapter uses a DataReader under the hood so your experience would likely be the same. The benefit of the DataAdapter is you cut out a lot of code that would need maintenance. This debate is a bit of a religious issue so definitely look around and decide what works best for your situation: http://blogs.msdn.com/memilavi/archive/2008/02/18/datareader-vs-dataset-the-real-question.aspx … Read more

Handle DBNull in C#

The shortest (IMHO) is: int stockvalue = (reader[“StockValue”] as int?) ?? 0; Explanation: If reader[“StockValue”] is of type int, the value will be returned, and the “??” operator will return the result If reader[“StockValue”] is NOT of type int (e.g. DBNull), null will be returned, and the “??” operator will return the value 0 (zero).

How can I easily convert DataReader to List? [duplicate]

I would suggest writing an extension method for this: public static IEnumerable<T> Select<T>(this IDataReader reader, Func<IDataReader, T> projection) { while (reader.Read()) { yield return projection(reader); } } You can then use LINQ’s ToList() method to convert that into a List<T> if you want, like this: using (IDataReader reader = …) { List<Customer> customers = reader.Select(r … Read more