What is the easiest way to bind a single row to a datatable to a detail view in C # asp.net?

I am currently copying a string into an empty datatable and binding it, but there is definitely a better way ...

+4
source share
2 answers

You don't need a data table to bind - you just need something like a list / enumerable. For example, if you know the line number:

DataRowView row = dt.DefaultView[1]; // second row detailsView1.DataSource = new DataRowView[] {row}; detailsView1.DataBind(); 

Note that we must use a DataRowView (rather than a DataRow ) to get only run-time properties (i.e. data from columns). If you have a DataRow , this approach can be easily wrapped in a utility method, for example, an extension method:

 public static DataRowView[] ForBinding(this DataRow row) { foreach (DataRowView rowView in row.Table.DefaultView) { if (ReferenceEquals(rowView.Row, row)) { return new DataRowView[] { rowView }; } } throw new ArgumentException("Row not found in the default view", "row"); } 

with:

 detailsView1.DataSource = row.ForBinding(); detailsView1.DataBind(); 
+5
source

yes, this is the easiest way :)

IMHO. If you want to display only one field, you can use the output parameters, but if you display more than one field in the detailed view, this is the easiest way.

+1
source

All Articles