The SqlDataSource control is a Web control used to access data stored in a relational database, such as Microsoft SQL Server™ and Oracle, as well as OLE DB and ODBC data sources.
The SqlDataSource control is typically used with ASP.NET Data Controls to display and optionally allow users to manipulate the data on an ASP.NET Web page, using little or no code.
The SqlDataSource uses ADO.NET classes to interact with any database supported by ADO.NET, including Microsoft SQL Server™ ( using the System.Data.SqlClient provider ), System.Data.OleDb, System.Data.Odbc, and Oracle ( using the System.Data.OracleClient provider ).
Using a SqlDataSource control allows you to access and manipulate data in an ASP.NET page without using ADO.NET classes directly.
You provide a connection string to connect to your database and define the SQL statements or stored procedures to work with the data.
<asp:sqldatasource id="uniqueID" runat="server"
connectionstring="<%$ ConnectionStrings: storedConnectionString %>"
selectcommand="sqlSelectCommand" />
At run time, the SqlDataSource automatically opens the database connection, executes the SQL statement or stored procedure, returns the selected data ( if any ), and then closes the connection.
When you configure a SqlDataSource control, you set the ProviderName property to the type of database ( defaults to System.Data.SqlClient when not specified ) and a valid ConnectionString that includes the needed information to connect to the database.
The contents of a connection string differ depending on what type of database the data source control is accessing.
For example, the SqlDataSource control requires a server name, database ( catalog ) name, and information about how to authenticate the user when connecting to a SQL Server™.
NOTE: For information on valid connection strings, see the ConnectionString property topics for the SqlConnection, OracleConnection, OleDbConnection, and OdbcConnection classes.
Instead of setting connection strings at design time as property settings in the SqlDataSource control, you can store them centrally as part of your application’s configuration settings ( in the web app’s web.config file ), using the connectionStrings configuration element.
<configuration ...>
<connectionStrings>
<add name="aspnet" connectionString="data source=serverAddress;
initial catalog=databseName; user id=userName; pwd=userPassword"
providerName="System.Data.SqlClient" />
...
</connectionStrings>
</configuration>
This enables you to manage connection strings independently of your ASP.NET code.
The following example shows how to set a connection to the SQL Server™ Northwind sample database using a connection string ( named aspnet
) stored in the <connectionStrings
> configuration element.
<asp:sqldatasource id="emps" runat="server"
connectionstring="<%$ ConnectionStrings: aspnet %>"
selectcommand="SELECT * FROM employees" />