DataRow: Select cell value by a given column name

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

    You can get the column value in VB.net

    Dim row As DataRow = fooTable.Rows(0)
    Dim temp = Convert.ToString(row("ColumnName"))
    

    And in C# you can use Jimmy's Answer, just be careful while converting it to ToString(). It can throw null exception if the data is null instead Use Convert.ToString(your_expression) to avoid null exception reference

    0 讨论(0)
  • 2020-12-15 15:31

    I find it easier to access it by doing the following:

            for (int i = 0; i < Table.Rows.Count-1; i++) //Looping through rows
            {
                var myValue = Table.Rows[i]["MyFieldName"]; //Getting my field value
    
            }
    
    0 讨论(0)
  • 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<T>(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;
      }
    
    0 讨论(0)
  • 2020-12-15 15:36

    Be careful on datatype. If not match it will throw an error.

    var fieldName = dataRow.Field<DataType>("fieldName");
    
    0 讨论(0)
  • 2020-12-15 15:40

    Which version of .NET are you using? Since .NET 3.5, there's an assembly System.Data.DataSetExtensions, which contains various useful extensions for dataTables, dataRows and the like.

    You can try using

    row.Field<type>("fieldName");
    

    if that doesn't work, you can do this:

    DataTable table = new DataTable();
    var myColumn = table.Columns.Cast<DataColumn>().SingleOrDefault(col => col.ColumnName == "myColumnName");
    if (myColumn != null)
    {
        // just some roww
        var tableRow = table.AsEnumerable().First();
        var myData = tableRow.Field<string>(myColumn);
        // or if above does not work
        myData = tableRow.Field<string>(table.Columns.IndexOf(myColumn));
    }
    
    0 讨论(0)
  • 2020-12-15 15:46

    This must be a new feature or something, otherwise I'm not sure why it hasn't been mentioned.

    You can access the value in a column in a DataRow object using row["ColumnName"]:

    DataRow row = table.Rows[0];
    string rowValue = row["ColumnName"].ToString();
    
    0 讨论(0)
提交回复
热议问题