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 先執行大小寫區分查詢。 若失敗,則進行第二次不區寫搜尋。 若找不到欄位編號,則擲出 。ArgumentException

GetOrdinal 假名寬度不敏感。

由於基於序數的查詢比命名查詢更有效率,因此在迴圈內呼叫 GetOrdinal 效率較低。 透過呼叫 GetOrdinal 一次並將結果指派到一個整數變數以用於迴圈,節省時間

適用於