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

时间:2017-05-29 10:32:52

标签: c# asp.net gridview webforms sqldatasource

在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);
}

抛出服务器错误:

  

&#39; GridView1&#39;的数据源ID必须是IDataSource类型的控件的ID。具有ID&{39; SqlDataSource1&#39;无法找到。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我认为命名sqlDataSource等于设置其ID,但事实并非如此。我必须明确设置 MyFlag added = xor & @new; // 1000 MyFlag removed = xor & old; // 0100