How to get data by SqlDataReader.GetValue by column name

C#Sql

C# Problem Overview


I use SqlDataReader.GetValue method to read values from DB:

Log.WriteLine("Value of CompanyName column:" + thisReader.GetValue(1)); 

As parameter GetValue get index of column. How could I specify Column Name instead index?

C# Solutions


Solution 1 - C#

Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]); 

Solution 2 - C#

You can also do this.

//find the index of the CompanyName column
int columnIndex = thisReader.GetOrdinal("CompanyName"); 
//Get the value of the column. Will throw if the value is null.
string companyName = thisReader.GetString(columnIndex);

Solution 3 - C#

thisReader.GetString(int columnIndex)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalgotView Question on Stackoverflow
Solution 1 - C#Mauricio SchefferView Answer on Stackoverflow
Solution 2 - C#RayView Answer on Stackoverflow
Solution 3 - C#user6943463View Answer on Stackoverflow