Sunday, February 24, 2008

Reusing the ASP .Net SqlDataSource for multiple web controls

Ok, I assume everyone knows how to use the SqlDataSource Control. So I'll dispatch with such details and get down to business. I had a sticky problem, I wanted to dump several web controls on a page without the hassle of creating multiple SqlDataSource Controls for each. In the past, I just created my own data layer and then reuse the connection objects. I decided it was code-reuse time and the built-in controls provided by .Net was a great opportunity. Since I was dealing with a control, I needed to programmatically change the command text to query the database for information. I had ten web controls to populate, each calling the same stored procedure to retrieve the data. Each call passed a modified sql parameter for a different set of data. So for simplicity, I'll present the steps here. 1. Include a SqlDataSource Control on your web page then configure it to use your data source information. Once configured, remove all the parameters except the connection string information. asp:SqlDataSource ID="sdsDataSource" runat="server" ConnectionString="" 2. In your Page_Load event, we're going to programmatically handle the calls then pass the new query data source to each item. 3. Below we setup our information programmatically. We set the DataSourceMode to Datareader for performance, then we call our stored procedure. We pass the necessary parameters then call our Select event to retrieve the data. //Property information sdsDataSource.DataSourceMode = SqlDataSourceMode.DataReader; sdsDataSource.SelectCommand = "perReadTypesByCategory"; sdsDataSource.SelectCommandType = SqlDataSourceCommandType.StoredProcedure; sdsDataSource.SelectParameters.Add("intTypeId", "31"); 4. Then we set the necessary control parameters, in this case a radio button list of propery items. rblProperyItems.DataMember = "DefaultView"; rblProperyItems.DataSource = sdsDataSource; rblProperyItems.DataTextField = "TypeDesc"; rblProperyItems.DataValueField = "TypeId"; rblProperyItems.DataBind(); 5. After the initial call, we need to clear out the sql parameter list, reset the parameters then make a call to refresh the data. Note we've only changed the information we needed, namely the parameter argument from 31 to 1. //Property Type information sdsDataSource.SelectParameters.Clear(); sdsDataSource.SelectParameters.Add("intTypeId", "1"); ddType.DataMember = "DefaultView"; ddType.DataSource = sdsDataSource; ddType.DataTextField = "TypeDesc"; ddType.DataValueField = "TypeId"; ddType.DataBind(); 6. Repeat Step 5 for multiple controls. 7. After you're done with the SqlDataSource Contorl you need to execute the Dispose method to release the resource. That's all there is to it. Good luck and hope this helps to all.

No comments: