6

I have been trying to find an answer to this question now for days and I find it hard to believe that this can't be done.

I want to get to the DataSet/DataTable that is built when a SqlDataSource.Select method is called automatically by the ASP.NET run-time when a page is being built.

I know I can run it in code behind but this makes a second trip to the database and I would really like to avoid this. Every example I have come across tell you to execute the Select method in the code behind.

Is there any way to access the data that has already been retrieved?

spajce
  • 7,044
  • 5
  • 29
  • 44
dscarr
  • 1,830
  • 2
  • 17
  • 21
  • 1
    You know, I tried to figure that out once, years ago, and decided it was just easier to bind the code in code-behind so I had easier access to the data set. If someone knows how to do this, it might change how I approach similar situaitons going forward. +1 for asking. – David Jan 11 '13 at 16:23
  • 2
    I wouldn't use that control at all. Instead use ADO.NET(f.e. `DataAdapter.Fill(DataTable)`) or a real ORM mapper like NHibernate or Entity framework. Anyway, it's not clear why you think that "code behind makes a second trip to the database". Use `if(!IsPostBack)` then. – Tim Schmelter Jan 11 '13 at 16:23
  • Don't really have a choice on the control. I need to make a change to an existing page and don't have the luxury of re-writing it. When you call the Select Method on the SqlDataSource it makes a trip to the database according to Microsoft http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.select.aspx – dscarr Jan 11 '13 at 17:15

1 Answers1

0

You can try with this code - based on ToTable method

DataView view = (DataView)SqlDataSource.Select(...);
DataTable table = view.ToTable();

Link : http://msdn.microsoft.com/en-us/library/wec2b2e6.aspx

Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51
  • This is the code I am talking about. Executing the Select method on the SqlDataSource retrieves the data from the database. (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.select.aspx) I have used this many times but in this case I'd like to avoid that second trip. – dscarr Jan 11 '13 at 16:31
  • "Avoid the second trip" implies that you've already got the data somewhere. In that case, can you intercept the call to `OnSelect()` during the prerender by providing a dummy `DataSource`, and substitute your own (cached?) dataset for the resulting data? – David R Tribble Jan 11 '13 at 20:18