2017-05-29 59 views
0

在aspx页面我有:如何在代码隐藏中创建SqlDataSource时将SqlDataSource引用到GridView控件?

<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.

回答

0

删除数据源ID从ASPX

<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(); 
} 
0

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

相关问题