GetValues
Int32numberOfValues
= DataReader.GetValues(Object[]values
);
This method provides an efficient way to retrieve all the values in a
row at once rather than access each column value separately. The
values are retrieved into an array of objects, which you must supply
as an argument. The GetValues( )
method returns
the number of values used to fill the array.
Before you use the GetValues( )
method, you should
make sure the array length is the correct size. If the array length
is less than the number of required columns, all the values will not
be retrieved. Instead, the available slots in the array are filled
with the corresponding column values, and all additional column
values are ignored. No exception is thrown. You can also pass an
object array that has a length greater than the number of columns
contained in the resulting row without generating an error.
The following example retrieves all the column values for a row into
an object array, and then adds this array to an
ArrayList
collection. The information for each row
is added to the ArrayList
in this fashion.
string SQL = "SELECT * FROM Customers"; SqlCommand cmd = new SqlCommand(SQL, con); ArrayList rows = new ArrayList(); con.Open(); SqlDataReader r = cmd.ExecuteReader(); while (r.Read()) { object[] values = new object[r.FieldCount]; r.GetValues(values); rows.Add(values); } con.Close(); Console.WriteLine("Data retrieved for " + rows.Count.ToString() + " rows");