Dataset column name and row value

Alvin picture Alvin · Feb 20, 2017 · Viewed 17.8k times · Source

I have a data set:

DataSet ds= _ExecuteQuery(contentCmd, CommandType.Text, contentParams);

// Column name
foreach (DataColumn column in ds.Tables[0].Columns)
{
  Console.WriteLine(column.ColumnName);
}

// Rows value
foreach (DataTable dt in ds.Tables){
     foreach (DataRow dr in dt.Rows){
        Console.Writeline(dr.Table.Rows[0]["name"].ToString());
     }
}

How can I retrieve rows value and column name of the row?

List<columnName, name>;

Answer

Dieter B picture Dieter B · Feb 20, 2017

I assume that you're looking for something like this:

        Dictionary<string, string> vals = new Dictionary<string, string>();

        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                vals.Add(dt.Columns[i].ColumnName, dr[dt.Columns[i].ColumnName].ToString());
            }
        }

Depends on your dataset, but this gives a full dictionary of each column name and corresponding value