Search code examples
c#asp.netgridviewwebformssqldatasource

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


In the aspx page I have:

<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. A control with ID 'SqlDataSource1' could not be found.


Solution

  • Remove data source id from aspx

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