DataTableReader.GetValues(Object[]) Метод

Определение

Заполняет массив объектов значениями столбцов текущей строки.

public:
 override int GetValues(cli::array <System::Object ^> ^ values);
public override int GetValues (object[] values);
override this.GetValues : obj[] -> int
Public Overrides Function GetValues (values As Object()) As Integer

Параметры

values
Object[]

Массив типа Object, в который будут скопированы значения столбцов из объекта DataTableReader.

Возвращаемое значение

Число значений столбцов, копируемое в этот массив.

Исключения

Переданный индекс находился вне диапазона от 0 до FieldCount - 1.

Предпринята попытка извлечения данных из удаленной строки.

Предпринята попытка чтения столбца закрытого объекта DataTableReader или получения доступа к нему.

Примеры

В следующем примере демонстрируется использование массива правильного размера для считывания всех значений из текущей строки в предоставленном DataTableReader. Кроме того, в примере демонстрируется использование массива фиксированного размера, который может быть меньше или больше числа доступных столбцов.

private static void TestGetValues(DataTableReader reader)
{
    // Given a DataTableReader, use the GetValues
    // method to retrieve a full row of data.
    // Test the GetValues method, passing in an array large
    // enough for all the columns.
    Object[] values = new Object[reader.FieldCount];
    int fieldCount = reader.GetValues(values);

    Console.WriteLine("reader.GetValues retrieved {0} columns.",
        fieldCount);
    for (int i = 0; i < fieldCount; i++)
        Console.WriteLine(values[i]);

    Console.WriteLine();

    // Now repeat, using an array that may contain a different
    // number of columns than the original data. This should work correctly,
    // whether the size of the array is larger or smaller than
    // the number of columns.

    // Attempt to retrieve three columns of data.
    values = new Object[3];
    fieldCount = reader.GetValues(values);
    Console.WriteLine("reader.GetValues retrieved {0} columns.",
        fieldCount);
    for (int i = 0; i < fieldCount; i++)
        Console.WriteLine(values[i]);
}
Private Sub TestGetValues(ByVal reader As DataTableReader)

    ' Given a DataTableReader, use the GetValues
    ' method to retrieve a full row of data.

    ' Test the GetValues method, passing in an array large
    ' enough for all the columns.
    Dim values(reader.FieldCount - 1) As Object
    Dim fieldCount As Integer = reader.GetValues(values)
    Console.WriteLine("reader.GetValues retrieved {0} columns.", _
         fieldCount)
    For i As Integer = 0 To fieldCount - 1
        Console.WriteLine(values(i))
    Next

    Console.WriteLine()

    ' Now repeat, using an array that may contain a different 
    ' number of columns than the original data. This should work correctly,
    ' whether the size of the array is larger or smaller than 
    ' the number of columns.

    ' Attempt to retrieve three columns of data.
    ReDim values(2)
    fieldCount = reader.GetValues(values)
    Console.WriteLine("reader.GetValues retrieved {0} columns.", _
         fieldCount)
    For i As Integer = 0 To fieldCount - 1
        Console.WriteLine(values(i))
    Next
End Sub

Комментарии

Для большинства приложений этот метод предоставляет эффективные средства для получения всех столбцов вместо извлечения каждого столбца по отдельности. Если вы хотите получить все значения столбцов из строки в DataTableReader, GetValues метод предоставляет наиболее эффективное решение.

Можно передать Object массив, содержащий меньше, чем количество столбцов, содержащихся в результирующей строке. В массив копируется только объем данных, Object который может содержать массив. Можно также передать Object массив, длина которого превышает количество столбцов, содержащихся в результирующей строке. В этом случае дополнительные элементы массива остаются неизменными при вызове метода .

Этот метод помещает DBNull в выходной массив пустые столбцы.

Применяется к