DataRow: Select cell value by a given column name

后端 未结 8 1529
小鲜肉
小鲜肉 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:46
    for (int i=0;i < Table.Rows.Count;i++)
    {
          Var YourValue = Table.Rows[i]["ColumnName"];
    }
    
    0 讨论(0)
  • 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<string>("Column#2");
    
    public static class DataRowExtensions
    {
        public static T GetCellValueByName<T>(this DataRow row, string columnName)
        {
            int index = row.Table.Columns.IndexOf(columnName);
            return (index < 0 || index > row.ItemArray.Count()) 
                      ? default(T) 
                      : (T) row[index];        
        }
    }
    
    0 讨论(0)
提交回复
热议问题