Trying to write the contents of a DataGrid to an html table.

Found sample code , but for DataGridView .

 private StringBuilder DataGridtoHTML(DataGridView dg) { StringBuilder strB = new StringBuilder(); //create html & table strB.AppendLine("<html><body><center><" + "table border='1' cellpadding='0' cellspacing='0'>"); strB.AppendLine("<tr>"); //cteate table header for (int i = 0; i < dg.Columns.Count; i++) { strB.AppendLine("<td align='center' valign='middle'>" + dg.Columns[i].HeaderText + "</td>"); } //create table body strB.AppendLine("<tr>"); for (int i = 0; i < dg.Rows.Count; i++) { strB.AppendLine("<tr>"); foreach (DataGridViewCell dgvc in dg.Rows[i].Cells) { strB.AppendLine("<td align='center' valign='middle'>" + dgvc.Value.ToString() + "</td>"); } strB.AppendLine("</tr>"); } //table footer & end of html file strB.AppendLine("</table></center></body></html>"); return strB;} 

The problem is that a DataGrid does not have a Rows property like a DataGridView .

Tell me how to iterate the lines for the DataGrid in the same way?

  • if this is WPF then it is much easier for you to use data binding and submit them to html - Ev_Hyper

2 answers 2

 var rowIndex = dataGrid.SelectedIndex; var row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(selectedIndex); 

or

 dataGrid.SelectedIndex = 3; var selectedRow= (DataRowView)dataGrid.SelectedItem; 
      for (int i = 0; i < dataGrid.Items.Count; i++) { DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i); }