using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace columnChange { class Program { static void Main(string[] args) { SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=Test;User ID=××××;Password=××××"); using (conn) { conn.Open(); SqlDataAdapter apt = new SqlDataAdapter("select top 10 * from news ", conn); DataTable tb = new DataTable(); apt.Fill(tb); DataTable tt = Col2Row(tb, "articleId"); } } /// <summary> /// 将DataTable行列转换 /// </summary> /// <param name="src">要转换的DataTable</param> /// <param name="columnHead">要作为Column的哪列</param> /// <returns></returns> public static DataTable Col2Row(DataTable src, int columnHead) { DataTable result = new DataTable(); DataColumn myHead = src.Columns[columnHead]; result.Columns.Add(myHead.ColumnName); for (int i = 0; i < src.Rows.Count; i++) { result.Columns.Add(src.Rows[i][myHead].ToString()); } // foreach (DataColumn col in src.Columns) { if (col == myHead) continue; object[] newRow = new object[src.Rows.Count + 1]; newRow[0] = col.ColumnName; for (int i = 0; i < src.Rows.Count; i++) { newRow[i + 1] = src.Rows[i][col]; } result.Rows.Add(newRow); } return result; } public static DataTable Col2Row(DataTable src, string columnHead) { for (int i = 0; i < src.Columns.Count; i++) { if (src.Columns[i].ColumnName.ToUpper () == columnHead.ToUpper()) return Col2Row(src, i); } return new DataTable(); } } }