BaseDataBoundControl.DataSource 属性
获取或设置对象,数据绑定控件从该对象中检索其数据项列表。
属性值
一个表示数据源的对象,数据绑定控件从该对象中检索其数据。默认为 空引用(在 Visual Basic 中为 Nothing)。
备注 当设置 DataSource 属性时,将调用 ValidateDataSource 方法。此外,如果数据绑定控件已经初始化,则调用 OnDataPropertyChanged 方法将 RequiresDataBinding 属性设置为 true。
无法通过主题或样式表主题设置此属性。有关更多信息,请参见 ThemeableAttribute 和 ASP.NET 主题和外观概述。
示例
<%@ Page language="C#" %>
<%@ import namespace="System.Data" %>
<%@ import namespace="System.Data.SqlClient" %>
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
// This example uses Microsoft SQL Server and connects
// to the Northwind sample database. The data source needs
// to be bound to the GridView control only when the
// page is first loaded. Thereafter, the values are
// stored in view state.
if(!IsPostBack)
{
// Declare the query string.
String queryString =
"Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]";
// Run the query and bind the resulting DataSet
// to the GridView control.
DataSet ds = GetData(queryString);
if (ds.Tables.Count > 0)
{
AuthorsGridView.DataSource = ds;
AuthorsGridView.DataBind();
}
else
{
Message.Text = "Unable to connect to the database.";
}
}
}
DataSet GetData(String queryString)
{
// Retrieve the connection string stored in the Web.config file.
String connectionString = ConfigurationManager.ConnectionStrings["NorthWindConnectionString"].ConnectionString;
DataSet ds = new DataSet();
try
{
// Connect to the database and run the query.
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
// Fill the DataSet.
adapter.Fill(ds);
}
catch(Exception ex)
{
// The connection failed. Display an error message.
Message.Text = "Unable to connect to the database.";
}
return ds;
}
</script>
<html>
<body>
<form runat="server">
<h3>GridView DataBind Example</h3>
<asp:label id="Message"
forecolor="Red"
runat="server"/>
<br/>
<asp:gridview id="AuthorsGridView"
autogeneratecolumns="true"
runat="server">
</asp:gridview>
</form>
</body>
</html>

浙公网安备 33010602011771号