2017-05-29 90 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";

相關問題