DataRow: Select cell value by a given column name

后端 未结 8 1530
小鲜肉
小鲜肉 2020-12-15 15:19

I have a problem with a DataRow that I\'m really struggling with.

The datarow is read in from an Excel spreadsheet using an OleDbConnection.

If I try to sele

8条回答
  •  再見小時候
    2020-12-15 15:48

    Hint

    DataTable table = new DataTable();
    table.Columns.Add("Column#1", typeof(int));
    table.Columns.Add("Column#2", typeof(string));
    table.Rows.Add(5, "Cell1-1");
    table.Rows.Add(130, "Cell2-2");
    

    EDIT: Added more

    string cellValue = table.Rows[0].GetCellValueByName("Column#2");
    
    public static class DataRowExtensions
    {
        public static T GetCellValueByName(this DataRow row, string columnName)
        {
            int index = row.Table.Columns.IndexOf(columnName);
            return (index < 0 || index > row.ItemArray.Count()) 
                      ? default(T) 
                      : (T) row[index];        
        }
    }
    

提交回复
热议问题