Download
Academy
Current location: Downcodes.com -> Academy -> Programming -> .NET tutorial -> Using the SqlDataReader Class(4)
Recommend
HOT TOP10
Using the SqlDataReader Class(4)
Date: 2008-1-4 Author: Hit: View:[Large font Middle font Small font]
More about the SqlDataReader Indexers
(Page 4 of 6 )

The implementation of the column-ordinal based indexer of the SqlDataReader class looks as follows:

public override object this[int i]

{

  get

{

  return this.GetValue(i);

 }

}

And the SqlDataReader's column-name based indexer implementation looks like this:

  public override object this[string name]

{

  get

{

   return this.GetValue(this.GetOrdinal(name));

 }

}
 

As you might have noted in the code example, we have used the ToString() method with the SqlDataReader's returned fields to create the ListItem object.

ListItem item = new ListItem(dataReader[1].ToString(), dataReader[0].ToString());

// or you can replace the above line of code with the following one

//ListItem item = new ListItem(dataReader["job_desc"].ToString(),

// dataReader["job_id"].ToString());

Both the column-ordinal based indexer and the column-name based indexer return an object data type so in our code we needed to call the SqlDataReader[Column Name or Column Ordinal].ToString() method to return a string value to create the List Item. What you should note about those indexers is the methods they use to return the field you are asking for, namely the GetValue() method and the GetOrdinal() method. The GetValue() method is used to get the field's value. It accepts the index of the field and returns it. In the column-name indexer the SqlDataReader uses the syntax this.GetValue(this.GetOrdinal(name)) in order to return the value of the field. The GetValue() method returns the field as an object data type too.

The SqlDataReader.GetOrdinal() method accepts a string value, which is the column name, and returns its ordinal. The GetOrdinal() method's return value is used as an argument to the SqlDataReader.GetValue() method, that accepts the column ordinal, to get the value of the field.

I think by now you have a better understanding of how these indexers return the field's data and you also know that using the column-ordinal indexer is faster than using the column-name indexer.

We may also use the methods that the indexers use directly, as in the following example.

(From: aspfree)

Relative article:
Using the SqlDataReader Class(6)
Using the SqlDataReader Class(1)
Using the SqlDataReader Class(2)
Using the SqlDataReader Class(3)
Using the SqlDataReader Class(5)
Relative software: