Sqldatasource control set dynamic Connectionstring in .aspx page only


Set Dynamic ConnectionString to SqlDataSource ASP.NET Control Inside GridView Template

Intro: The SqlDataSource control enables you to use a Web server control to access data that is located in a relational database. You can use the SqlDataSource control with data-bound controls such as the GridView, FormView, and DetailsView controls to display and manipulate data on an ASP.NET Web page, using little or no code.


Here in this article I am writing how to set Dynamically ConnectionString Attribute on  SqlDataSource ASP.NET Control. Setting connection string for SqlDataSource control can de done programmatically in the code-behind ie (.aspx.cs) file.


On Page_Load:

If the SqlDataSource control is  inside the FooterTemplate of a GridView control then it will not be accessible at Page_Load. Here’s the challenging task how to set ConnectionString on SqlDatasource control under Gridview Templates.
By following below steps you can achieve this:
Step 1:
Here sample code of gridview templates:

<asp:dropdownlist autopostback=”True” datasourceid=”sqldsWorkcategory” datatextfield=”name_wt” datavaluefield=”id_wt” id=”cmbfWorkCategory” onselectedindexchanged=”cmbfWorkCategory_SelectedIndexChanged” runat=”server” width=”118″>
<asp:sqldatasource connectionstring=”&lt;%$ RepConnectionString: ” getconnection=”getconnection”>”
id=”sqldsWorkcategory” runat=”server”
selectcommand=”SELECT [id_wt], [name_wt] FROM [yourtablename]”&gt;

Step 2:
Now edit your web.config file
As i have many connection so have make a diifernt XML file to store all connections key

<configsource onstring.xml=”onstring.xml” pp_data=”pp_data”>
<!– Now Add this pieace of code under Compilation as u can see. –>
<compilation debug=”true” targetFramework=”4.0″>
<add expressionprefix=”RepConnectionString” type=”RepConnectionStringExpressionBuilder”>

Step 3:
Add class file inside App_code.
Have named as CodeExpressionBuilder.cs.

Note: using System.CodeDom; is needed
if u find error then add refference or google for this namespace,

Code of CodeExpressionBuilder.cs
just copy as it is.

This will set your dynamic ConnectionString for SqlDataCource control on .aspx page.
Debug n get the flow of code.Enjoy…….