DataRow: Select cell value by a given column name

后端 未结 8 1540
小鲜肉
小鲜肉 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:35

    On top of what Jimmy said, you can also make the select generic by using Convert.ChangeType along with the necessary null checks:

    public T GetColumnValue(DataRow row, string columnName)
      {
            T value = default(T);
            if (row.Table.Columns.Contains(columnName) && row[columnName] != null && !String.IsNullOrWhiteSpace(row[columnName].ToString()))
            {
                value = (T)Convert.ChangeType(row[columnName].ToString(), typeof(T));
            }
    
            return value;
      }
    

提交回复
热议问题