[英]How to refer SqlDataSource to GridView control, when SqlDataSource is created in code-behind?
In the aspx page I have: 在aspx页面中,我有:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
</asp:GridView>
In the code-behind page: 在代码隐藏页面中:
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);
}
Which throws a server error: 这会引发服务器错误:
The DataSourceID of '
GridView1
' must be the ID of a control of type IDataSource.GridView1
的DataSourceID必须是IDataSource类型的控件的ID。 A control with ID 'SqlDataSource1
' could not be found.找不到ID为
SqlDataSource1
的控件。
Remove data source id from aspx 从aspx中删除数据源ID
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
do it from code 用代码做
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();
}
I thought naming the sqlDataSource is equal to setting its ID, it's not. 我以为命名sqlDataSource等于设置其ID,不是。 I have to explicitly set
SqlDataSource.ID = "SqlDataSource";
我必须显式设置
SqlDataSource.ID = "SqlDataSource";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.