Portal Engine Questions on portal engine and web parts.
Version 5.x > Portal Engine > Consuming data from an SQLDataSource in a custom webpart View modes: 
User avatar
Member
Member
nvpat - 8/22/2011 7:05:11 PM
   
Consuming data from an SQLDataSource in a custom webpart
Hello all.

I need to write a custom web part which will depend on some data retrieved by a SQLDataSource web part on the same page. Assuming that the name of the DataSource control is passed as a parameter to my web part, what do I need to do programatically to access the result set retrieved by that data source control?

Thanks.

User avatar
Member
Member
nvpat - 8/23/2011 1:32:53 PM
   
RE:Consuming data from an SQLDataSource in a custom webpart
I'd like to clarify. The SQLDataSource itself is not contained in a web part. It is simply on the same page as a custom web part I've written. I need to access, programatically in my web part, the data set contained by that SQLDataSource. I need to access the data directly, not through a repeater or other listing control.

How is that done? Unfortunately the source code for the BasicRepeater control is not included in the project, as far as I can tell, so I can't look to see how it does it.

Thanks.

User avatar
Member
Member
kentico_michal - 8/25/2011 1:06:09 AM
   
RE:Consuming data from an SQLDataSource in a custom webpart
Hello,

You can take advantage of using CMS.GlobalHelper.RequstStockHelper class that provides two methods Add / GetItem. The Add method allows you to insert a reference to some object into HttpContext.Current.Items collection whereas GetItem can be used to retrieve the object reference.

So, you can modify the SQLDataSource web part (~\CMSWebParts\DataSources\SQLDataSource.ascx.cs) and implement the OnInit method in which you can add a reference to the SQLDataSource control to HttpContext.Current.Items collection:


protected override void OnInit(EventArgs e)
{
CMS.GlobalHelper.RequestStockHelper.Add("SqlDataSource", this.srcSQL);
base.OnInit(e);
}



the srcSQL is the ID of the SqlDataSource control used in SqlDataSource web part.

Now, you should be able to get this SqlDataSource control and its DataSource in your custom web part:


protected void Page_Load(object sender, EventArgs e)
{
if (CMS.GlobalHelper.RequestStockHelper.Contains("SqlDataSource"))
{
object o = CMS.GlobalHelper.RequestStockHelper.GetItem("SqlDataSource");
CMS.Controls.SQLDataSource sqlDataSource = o as CMS.Controls.SQLDataSource;
if (sqlDataSource != null)
{
DataSet dataSource = sqlDataSource.DataSource as DataSet;
if (!DataHelper.DataSourceIsEmpty(dataSource))
{
// custom code
}
}
}
}


Best regards,
Michal Legen

User avatar
Member
Member
nvpat - 8/25/2011 7:30:23 PM
   
RE:Consuming data from an SQLDataSource in a custom webpart
Thanks Michal! That worked great.