golds
golds

Reputation: 53

Defining ConnectionString in asp SqlDataSource

I have my database connectivity which I define under <appSettings> in web.comfig:

<appSettings>
    <add key="ConnStr" 
         value="Data Source=dsk-159\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"/>
</appSettings>

But the problem is that I am unable to access it from my aspx page as I am trying like this

<asp:SqlDataSource ID="SqlDataSource2" runat="server" 
     ConnectionString="<%$ ConnectionStrings:goldsConnectionString %>"
     SelectCommand="SELECT distinct TechnologyId , [TechnologyName], [ChildId] FROM [TreeTable] where childid is null AND technologyid in(@hid1)">
     <SelectParameters>
         <asp:ControlParameter ControlID="hid1" Name="hid1" DefaultValue="23" />
     </SelectParameters>

In place of <connectionStrings> I want to define it in <appSettings>

Plesae tell the correct syntax.

Upvotes: 5

Views: 17749

Answers (4)

Pankaj
Pankaj

Reputation: 685

Your web.config should be like below:

<appSettings>
<add key="ConnStr" value="Server=yourservername;Database=yourdatabasename;UID=yourusername;Password=youruserpassword"/>
</appSettings>

And your .aspx file should like following:

<asp:GridView ID="grd" runat="server" DataSourceID="SqlDataSource2">
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ appSettings:ConnStr %>" SelectCommand="SELECT * FROM ticketmaster"></asp:SqlDataSource>

Upvotes: 4

Sandeep Dhanush
Sandeep Dhanush

Reputation: 1

you can set the connection string in your code-behind page

SqlDataSource2.ConnectionString =
System.Configuration.ConfigurationManager.AppSttings["ConnStr"];

Upvotes: 0

David
David

Reputation: 432

Try to change the aspx part to this:

<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnStr %>" SelectCommand="SELECT distinct TechnologyId , [TechnologyName], [ChildId] FROM [TreeTable] where childid is null AND technologyid in(@hid1)">
<SelectParameters>
<asp:ControlParameter ControlID="hid1" Name="hid1" DefaultValue="23" />
</SelectParameters>

I have done 2 things:

  1. removed the tags.
  2. changed the connection string name to match the name in the web.config
    (goldsConnectionString-->ConnStr)

Upvotes: 1

DGibbs
DGibbs

Reputation: 14618

You know you can set the connection string in the code behind rather than inline, it's much cleaner.

SqlDataSource2.ConnectionString = 
System.Configuration.ConfigurationManager.AppSettings["ConnStr"];

Consider reading up on ConfigurationManger.AppSettings

Upvotes: 5

Related Questions