Faire une boucle à travers un DataTable

Bien. J’ai un DataTable avec plusieurs colonnes et plusieurs lignes.

Je veux parcourir le DataTable de manière dynamic, la sortie devrait ressembler à ceci, sans les accolades:

Name (DataColumn) Tom (DataRow) Peter (DataRow) Surname (DataColumn) Smith (DataRow) Brown (DataRow) foreach (DataColumn col in rightsTable.Columns) { foreach (DataRow row in rightsTable.Rows) { //output } } 

J’ai tapé ça et remarqué que ça ne marcherait pas. Quelqu’un peut-il s’il vous plaît donner des conseils sur une meilleure façon de le faire?

 foreach (DataColumn col in rightsTable.Columns) { foreach (DataRow row in rightsTable.Rows) { Console.WriteLine(row[col.ColumnName].ToSsortingng()); } } 
  foreach (DataRow row in dt.Rows) { foreach (DataColumn col in dt.Columns) Console.WriteLine(row[col]); } 

S’il vous plaît essayez le code suivant ci-dessous:

 //Here I am using a reader object to fetch data from database, along with sqlcommand onject (cmd). //Once the data is loaded to the Datatable object (datatable) you can loop through it using the datatable.rows.count prop. using (reader = cmd.ExecuteReader()) { // Load the Data table object dataTable.Load(reader); if (dataTable.Rows.Count > 0) { DataColumn col = dataTable.Columns["YourColumnName"]; foreach (DataRow row in dataTable.Rows) { strJsonData = row[col].ToSsortingng(); } } } 

Si vous souhaitez modifier le contenu de chaque cellule d’un datatable, vous devez créer un autre datatable et le lier comme suit à l’aide de “Import Row”. Si nous ne créons pas une autre table, il générera une exception disant “La collection a été modifiée”.

Considérons le code suivant.

 //New Datatable created which will have updated cells DataTable dtUpdated = new DataTable(); //This gives similar schema to the new datatable dtUpdated = dtReports.Clone(); foreach (DataRow row in dtReports.Rows) { for (int i = 0; i < dtReports.Columns.Count; i++) { string oldVal = row[i].ToString(); string newVal = "{"+oldVal; row[i] = newVal; } dtUpdated.ImportRow(row); } 

Cela aura toutes les cellules précédant avec Paranthesis ({)