簡體   English   中英

獲取帶有名稱的DataTable列的索引

[英]get index of DataTable column with name

我有一些代碼通過列名設置DataRow中的單元格的值,即

row["ColumnName"] = someValue;

我還要將列中此行的值設置在上面找到的那一行的右側。 顯然,如果我通過索引而不是按列名獲取單元格,這將很容易。 那么有沒有辦法從列名中獲取列索引,從而允許我這樣做:

row[index + 1] = someOtherValue;

即,我是否需要在最初創建表時創建某種列索引和列名稱的字典,或者我可以稍后從列名稱中獲取索引而不執行此操作?

您可以使用DataColumn.Ordinal來獲取DataTable列的索引。 因此,如果您需要提到的下一列,請使用Column.Ordinal + 1

row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;

試試這個:

int index = row.Table.Columns["ColumnName"].Ordinal;

您只需使用DataColumnCollection.IndexOf即可

這樣您就可以按名稱獲取所需列的索引,然后將其與行一起使用:

row[dt.Columns.IndexOf("ColumnName")] = columnValue;

我寫了一個DataRow的擴展方法,通過列名獲取對象。

public static object Column(this DataRow source, string columnName)
{
    var c = source.Table.Columns[columnName];
    if (c != null)
    {
        return source.ItemArray[c.Ordinal];
    }

    throw new ObjectNotFoundException(string.Format("The column '{0}' was not found in this table", columnName));
}

它的召喚如下:

DataTable data = LoadDataTable();
foreach (DataRow row in data.Rows)
{        
    var obj = row.Column("YourColumnName");
    Console.WriteLine(obj);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM