指定连接字符串
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT * FROM [Categories]">
</asp:SqlDataSource>
<body>
<form id="form1" runat="server">
<asp:SqlDataSource
id="SqlDataSource1"
runat="server"
DataSourceMode="DataReader"
ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
SelectCommand="SELECT LastName FROM Employees">
</asp:SqlDataSource><asp:ListBox
id="ListBox1"
runat="server"
DataTextField="LastName"
DataSourceID="SqlDataSource1">
</asp:ListBox></form>
使用的数据库支持存储过程,则可以将 SelectCommand 属性设置为存储过程的名称,并将 SelectCommandType 属性设置
</body>
</html>
为 StoredProcedure,以指示 SelectCommand 属性引用一个存储过程。下面的示例演示一个可在 SQL Server 中创建的简单
存储过程:
若要配置 SqlDataSource 以使用此存储过程,请将 SelectCommand 文本设置为“sp_GetAllEmployees”,
并将 SelectCommandType 属性设置为 StoredProcedure。
通过将添加到 SelectParameters 集合的参数与 SelectCommand 查询中的占位符关联起来,SqlDataSource 控件支持参数化
SQL 查询。参数值可从页面上的其他控件、会话状态、用户配置文件以及其他元素中读取。有关更多信息,请参见
对 SqlDataSource 控件使用参数。SELECT * FROM Orders WHERE EmployeeID = @empid<body>
<form id="form1" runat="server"><p><asp:dropdownlist
id="DropDownList1"
runat="server"
autopostback="True">
<asp:listitem selected="True">Sales Representative</asp:listitem>
<asp:listitem>Sales Manager</asp:listitem>
<asp:listitem>Vice President, Sales</asp:listitem>
</asp:dropdownlist></p><asp:sqldatasource
id="SqlDataSource1"
runat="server"
connectionstring="<%$ ConnectionStrings:MyNorthwind%>"
selectcommand="SELECT LastName FROM Employees WHERE Title = @Title">
<selectparameters>
<asp:controlparameter name="Title" controlid="DropDownList1" propertyname="SelectedValue"/>
</selectparameters>
</asp:sqldatasource><p><asp:listbox
id="ListBox1"
runat="server"
datasourceid="SqlDataSource1"
datatextfield="LastName">
</asp:listbox></p></form>
</body>
SqlDataSource 控件的 DataSourceMode 属性确定 SqlDataSource 控件如何维护数据。默认情况下,DataSourceMode 属性设置为 DataSet,表示通过 SqlDataSource 控件将从数据库返回的结果集存储到服务器内存中。当 SqlDataSource 控件在 DataSet 模式下检索数据时,关联的数据绑定控件(如 GridView 和 DetailsView)可提供丰富的数据显示功能,如自动排序和分页。
另外,还可以将 DataSourceMode 属性设置为 DataReader,表示不将结果集存储在内存中。如果不需要将结果集保存在服务器的内存中,请使用 DataReader 模式。
下面的代码示例演示在不需要排序、分页或筛选时,如何将 SqlDataSource 控件的 DataSourceMode 属性设置为 DataReader。
详情参见 msdn
http://msdn.microsoft.com/zh-cn/library/w1kdt8w2%28v=VS.90%29.aspx