NewBie
NewBie

Reputation: 1844

GridView called from a user control is null on page reload

I'm having a usercontrol within the aspx page. In the usercontrol im binding the gridview with a datatable. This thing throws nullreference exception on page reload. The gridview object is null. I couldnt find help anywhere.

The code in cs page of the user control is:

If(!IsPostBack)
{

DataTable dt = GetDataTable();
JobListGrid.DataSource = dt;   //This throws error cause the joblistgrid is null
JobListGrid.DataBind();   

}

aspx code:

<asp:GridView ID="JobListGrid" runat="server">
            <Columns></Columns>
            </asp:GridView>

Am i missing something? Please help.

Upvotes: 2

Views: 1730

Answers (2)

MeTitus
MeTitus

Reputation: 3428

From the MSDN:

http://msdn.microsoft.com/en-us/library/ms178472.aspx

"The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page. Use the OnLoad event method to set properties in controls and to establish database connections."

This is not where you want to to that binding because you are not guaranteed that the control is loaded already, unless you use the load for the control not the load for the page.

Try the PreRender event instead.

enter image description here

Upvotes: 1

zey
zey

Reputation: 6103

Try this , you may need data field name in your grid bound column .

<asp:DataGrid><Columns><asp:BoundColumn DataField="YourDatabaseColumnName"></asp:BoundColumn></Columns></asp:DataGrid>

Upvotes: 0

Related Questions