Preferred Language:

Listing 9.4 - Web.Config

Illustrates how to store a connection string in the web.config configuration file.

Listing 9.4 - Web.config
Copy

<?xml version="1.0"?>
<configuration>
    <connectionStrings>
        <add name="Movies" connectionString="Data Source=.\SQLEXPRESS;
      AttachDbFilename=|DataDirectory|MyDatabase.mdf;Integrated Security=True;
User Instance=True" />
    </connectionStrings>
</configuration>

The following page uses the connection string stored in the web configuration above.

Listing 9.5 - ShowMovies.aspx (C#)
Copy

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Movies</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:GridView
        id="grdMovies"
        DataSourceID="srcMovies"
        Runat="server" />
        
    <asp:SqlDataSource
        id="srcMovies"
        SelectCommand="SELECT * FROM Movies"
        ConnectionString="<%$ ConnectionStrings:Movies %>"
        Runat="server" />
    
    </div>
    </form>
</body>
</html>