在代码隐藏中创建 SqlDataSource 时,如何将 SqlDataSource 引用到 GridView 控件?

How to refer SqlDataSource to GridView control, when SqlDataSource is created in code-behind?

在我的aspx页面中:

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
</asp:GridView>

在代码隐藏页面中:

protected void Page_Load(object sender, EventArgs e)
{
    SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager
    .AppSettings["MyConnectionString"];
    SqlDataSource1.SelectCommand = "SELECT * FROM my_table_name";
    this.Controls.Add(SqlDataSource1);
}

引发服务器错误:

The DataSourceID of 'GridView1' must be the ID of a control of type IDataSource. A control with ID 'SqlDataSource1' could not be found.

从 aspx 中删除数据源 ID

<asp:GridView ID="GridView1" runat="server">
</asp:GridView>

从代码开始

protected void Page_Load(object sender, EventArgs e)
{
    SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager
    .AppSettings["MyConnectionString"];
    SqlDataSource1.ID = "SqlDataSource1";
    this.Page.Controls.Add(SqlDataSource1);
    SqlDataSource1.SelectCommand = "SELECT * FROM my_table_name";
    GridView1.DataSource = SqlDataSource1;
    GridView1.DataBind();
}

我以为命名 sqlDataSource 就等于设置它的 ID,其实不是。我必须明确设置 SqlDataSource.ID = "SqlDataSource";