开发者

Programmatic Gridview Understanding

开发者 https://www.devze.com 2023-04-13 02:22 出处:网络
This may be a fairly simple question, but I can\'t seem to find the answer I\'m looking for. I\'ve been working with a GridView control programmatically, loading it from a dataset in the code behind.

This may be a fairly simple question, but I can't seem to find the answer I'm looking for.

I've been working with a GridView control programmatically, loading it from a dataset in the code behind. So it's a fairly simple process, instantiate a new Gridview, load the Dataset, bind the data, and then load the control.

However, I'm running into an issue where I can't load directly into the GridView from the code. In the .aspx file I have a simple:

<asp:GridView ID="Supp_Data" runat="server" /> 

In the code behind my creation of the GridView is as follows:

Supp_Data = new GridView();
Supp_Data = OutsideClass.GetData(str_sql); 
//Add other features here (such as AllowSorting, GridLines, PageSize, etc.)

Supp_Data.DataBind();

And in my outside class:

public static GridView GetData(string str_sql)
{
    // string str_sql is simply the sql query that we will get the dataset with.         

    OdbcConnection dbc_conn = ODBC_Conn("");  //This simply instantiates the connection
    OdbcCommand dbc_cmd = null;
    OdbcDataAdapter dbc_adpt = null;
    DataSet dta_ds = new DataSet();
    GridView ret_val = new GridView();
    try
    {
        if (dbc_conn.State != System.Data.ConnectionState.Open) { dbc_conn.Open(); }
        dbc_cmd = new OdbcCommand(str_sql, dbc_conn);
        dbc_adpt = new OdbcDataAdapter(dbc_cmd);
        dbc_adpt.Fill(dta_ds);
        ret_val.DataSource = dta_ds;
        ret_val.DataBind();
        dbc_conn.Close();
    }
    catch (Exception e) 
    {
        string tst_msg = e.Message;
    }
    return ret_val; 
}

But this doesn't display the grid at all.

Now, as a workaround (which displays the data), adding a PlaceHolder in the .aspx file and using PlaceHolder.Controls.Add(Supp_Data) displays the data just fine.

So my actual question is, why doesn't the data get displayed in the GridView, but has no problem displaying in the PlaceHolder? Does it have something to do with the Page Life Cycle that I'm overlooking (I tried with both Page_Load and Page_Init with the same results)? This would definitely help my overall understanding of this process. I just don't understand why it would work near开发者_开发知识库 perfectly with one but not with the other.

Thanks for any information.


You shouldn't do a 'new' on the GridView, just populate it's DataSource and call DataBind. The object that the page was referencing is being overwritten in your function call so it has nothing to display.

0

精彩评论

暂无评论...
验证码 换一张
取 消