51

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?

3 Answers 3

92
Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]); 
Sign up to request clarification or add additional context in comments.

6 Comments

I used as workaround following - Log.WriteLine("Value of CompanyName column:" + thisReader.GetValue(thisReader.GetOrdinal("CompanyName"))); What [] means?
I don't understand the syntax "thisReader["CompanyName"]). It is in no way logical. Logical would be "thisReader.fields("CompanyName").value". But who am I to judge...
@tmighty: This is a very common notation for indexed collections, not only in C#. The index will often be an integer, but it can also be of another type, such as string.
Note to self, internally this does return GetValue(GetOrdinal(name)); reference referencesource.microsoft.com/#system.data/system/data/…
|
55

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

6 Comments

I was thinking in which case this could have more benefit then directly reading data from reader as thisReader["CompanyName"]. Can you please give any specific case for it? Thanks a lot btw.
@curiousBoy doing it this way will make it easier to check if the column exists, also makes sure the value you are selecting is in the correct dataformat e.g GetString, GetInt32 it doesnt just return an object you then have to cast. This is why i would use this method
@DavidMolyneux thx for your comment, as far as I understand from your explanation, it basically do "null check" for the string and throws an error in case of the value is null. This also makes me thing that this is just for the type of string. Other than that, for instance : "int productQuantiy = thisReader["ProductQuantity"] " would throw an error if the ProductQuantity doesn't have a valid int value, wouldn't it? thx again.
@curiousBoy 'int productQuantiy = thisReader["ProductQuantity"]' wouldnt work the compiler wont let you assign an object to a int you would have to parse/convert the object first.
For performance reasons, Microsoft now recommends you call your GetOrdinal outside your read loop, and only call GetString(int) inside the loop
|
-4

thisReader.GetString(int columnIndex)

1 Comment

Please add some explanation of how this answer actually solves the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.