The DataReader object represents the results of a database query. You get a DataReader by calling a Command object’s ExecuteReader() method.
Whether a DataReader represents any rows by checking the HasRows property or calling the Read() method. The Read() method returns true when the DataReader can advance to a new row.
The DataReader represents a single row of data at a time. To get the next row of data, you need to call the Read() method. When you get to the last row, the Read() method returns False.
There are multiple ways to refer to the columns returned by a DataReader.
If you want to retrieve the value of the Title column for the current row represented by a DataReader, then you can use any of the following methods:
string title = (string)reader[“<FieldName>”];
string title = (string)reader[0];
string title = reader.GetString(0);
SqlString title = reader.GetSqlString(0);
The first method returns the Title column by name. The value of the Title column is returned as an Object. Therefore, you must cast the value to a string before you can assign the value to a string variable.
The second method returns the Title column by position. It also returns the value of the Title column as an Object, so you must cast the value before using it.
The third method returns the Title column by position. However, it retrieves the value as a String value. You don’t need to cast the value in this case.
The fourth method returns the Title column by position. However, it returns the value as a SqlString rather than a normal String. A SqlString represents the value using the specialized data types defined in the System.Data.SqlTypes namespace.
DataReader Object in ASP.Net C#
Hot on Web: