DataTableReader.GetOrdinal(String) 方法

定義

提供資料行的名稱,取得資料行序數。

public:
 override int GetOrdinal(System::String ^ name);
public override int GetOrdinal (string name);
override this.GetOrdinal : string -> int
Public Overrides Function GetOrdinal (name As String) As Integer

參數

name
String

資料行名稱。

傳回

以零為基底的資料行序數。

例外狀況

嘗試在關閉的 DataTableReader 中讀取或存取資料行。

指定的名稱不是有效的資料行名稱。

範例

如果您只有數據行名稱,在此情況下,數據行名稱是使用者提供的,而且您必須從數據行擷取資訊,您可以使用如下所示的程式來擷取必要的資訊。 在這裡範例中,程式會接受資料行名稱,並傳回 中目前數據列 DataTableReader 包含在該資料列中的數據:

private static object GetValueByName(
    DataTableReader reader, string columnName)
{
    // Consider when to use a procedure like this one carefully:
    // if you're going to retrieve information from a column
    // in a loop, it would be better to retrieve the column
    // ordinal once, store the value, and use the methods
    // of the DataTableReader class directly.
    object columnValue;

    try
    {
        int columnOrdinal = reader.GetOrdinal(columnName);
        columnValue = reader.GetValue(columnOrdinal);
    }
    catch (ArgumentException ex)
    {
        // Throw all other errors back out to the caller.
        columnValue = null;
    }
    return columnValue;
}
Private Function GetValueByName( _
   ByVal reader As DataTableReader, _
   ByVal columnName As String) As Object

   ' Consider when to use a procedure like this one carefully:
   ' If you're going to retrieve information from a column
   ' in a loop, it would be better to retrieve the column
   ' ordinal once, store the value, and use the methods
   ' of the DataTableReader class directly. 
   Dim columnValue As Object

   Try
      Dim columnOrdinal As Integer = reader.GetOrdinal(columnName)
      columnValue = reader.GetValue(columnOrdinal)
   Catch ex As ArgumentException
      ' Throw all other errors back out to the caller.
      columnValue = Nothing
   End Try
   Return columnValue
End Function

備註

由於類別所提供的 DataTableReader 大部分方法都必須提供序數數據行編號,因此您可以使用 GetOrdinal 方法來擷取數據行編號,指定數據行的名稱。

GetOrdinal 會先執行區分大小寫的查閱。 如果失敗,則會進行第二個不區分大小寫的搜尋。 如果找不到資料列編號, IndexOutOfRangeException 則會擲回 。

GetOrdinal 不區分假名寬度。

因為根據序數進行查閱比具名查閱更有效率,所以在迴圈內呼叫 GetOrdinal 的效率不佳。 呼叫 GetOrdinal 一次並將結果指派給整數變數,以節省時間,以在迴圈內使用

適用於