nsphere perspectives
printer friendly version     email to a friend    

SqlDataSource

by Miles Overn

Microsoft Links

MSDN SqlDataSource Overview
MSDN SqlDataSource Class
The SqlDataSource control is just that; a control. And it's a non-visual control to boot!

So what does that mean to us? Well, for starters it means that we have to use a visual control, such as FormView, GridView, or a DropDownList, to actually render the representation of the data returned by the SqlDataSource control. Otherwise, the representation of the data will be returned, but not displayed.

(Having said that, it is possible to instantiate several SqlDataSources and then programatically select the one you wish to populate a particular visual control with, such as a DropDownList.)

So, with as little as two lines of code, you can display a grid of data inside a web page; one line declares a GridView (visual control) and sets its datasource to the SqlDataSource, and the other line defines the SqlDataSource itself:

          <asp:GridView
            ID="grdStuff"
            DataSourceID="srcStuff"
            Runat=Server />
<asp:SqlDataSource ID="srcStuff" SelectCommand="SELECT FieldA, FieldB FROM Stuff" ConnectionString="yourconnectionstring" Runat=Server />
Now, granted, this would produce an extremely spartan page, but it would be a page displaying a grid containing a representation of both FieldA and FieldB of each record in the Stuff table of the database referenced in your connection string.


The SqlDataSource can be used for any Sql relational database, not just Microsoft's SQL Server. Other possibilities are Oracle, Microsoft SQL Server Express, Microsoft Access, etc.

The SqlDataSource control is, of course, able to do more than this simple read operation on a table. You can also execute commands (Select, Update, Delete, Insert) and set parameters for each of those commands. Additionally, you can change the command type to allow for calling stored procedures in place of inline SQL statements.