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

前端 未结 5 748
夕颜
夕颜 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:14

    In my case needed also to add a name to all columns of the new table. I wrote a function to generate a transposed table like this:

    static public DataTable Transpose(DataTable inputTable, List newColumnNames)
    {
        DataTable outputTable = new DataTable();
    
        ///You should also verify if newColumnsNames.Count matches inputTable number of row
    
        //Creates the columns, using the provided column names.
        foreach (var newColumnName in newColumnNames)
        {
            outputTable.Columns.Add(newColumnName, typeof(string));
        }
    
        foreach (DataColumn inputColumn in inputTable.Columns)
        {
            //For each old column we generate a row in the new table
            DataRow newRow = outputTable.NewRow();
    
            //Looks in the former header row to fill in the first column
            newRow[0] = inputColumn.ColumnName.ToString();
    
            int counter = 1;
            foreach (DataRow row in inputTable.Rows)
            {
                newRow[counter] = row[inputColumn.ColumnName].ToString();
                counter++;
            }
            outputTable.Rows.Add(newRow);
        }
    
        return outputTable;
    
    }
    

提交回复
热议问题