Is it possible to switch rows and columns in a datagridview?

前端 未结 5 747
夕颜
夕颜 2020-12-03 22:35

I have 10 records of data in a DataTable which has 3 fields \"Foo\", \"Bar\", and \"Baz\".

If I connect wire this into a DataGridView I see 10 rows and 3 columns, an

5条回答
  •  无人及你
    2020-12-03 23:03

    You can create new DataTable, add appropriate number of collumns and then copy values from one table to the other, just swap rows and colums.

    I don't think you can set row header in the same way you can set column header (or at least I don't know how), so you can put the field names in separate colum.

    DataTable oldTable = new DataTable();
    
    ...
    
    DataTable newTable = new DataTable();
    
    newTable.Columns.Add("Field Name");
    for (int i = 0; i < oldTable.Rows.Count; i++)
        newTable.Columns.Add();
    
    for (int i = 0; i < oldTable.Columns.Count; i++)
    {
        DataRow newRow = newTable.NewRow();
    
        newRow[0] = oldTable.Columns[i].Caption;
        for (int j = 0; j < oldTable.Rows.Count; j++)
            newRow[j+1] = oldTable.Rows[j][i];
        newTable.Rows.Add(newRow);
    }
    
    dataGridView.DataSource = newTable;
    

提交回复
热议问题