DataGrid DataSource is null on postback

N

Narshe

If I create a datagrid, and set a source and bind it, the data shows up
fine. When a postback occurs, the DataGrid.DataSource == null. Is there
something in the web.config I'm missing?

This is on asp.net 2.0.
 
N

Narshe

With code. In the PageIndexChanged event, the datagrid's datasource is
null.

public partial class DataGrid : System.Web.UI.Page
{
private System.Collections.ArrayList list;

protected void Page_Load(object sender, EventArgs e)
{
if( !Page.IsPostBack )
{
list = new ArrayList();
list.Add( "one" );
list.Add( "two" );
list.Add( "three" );
list.Add( "four" );
list.Add( "five" );

this.DataGrid1.DataSource = list;
this.DataGrid1.DataBind();
}
}

protected void DataGrid1_PageIndexChanged( object source,
DataGridPageChangedEventArgs e )
{
this.DataGrid1.CurrentPageIndex = e.NewPageIndex;
this.DataGrid1.DataBind();
}
}
 
G

Guest

Hello,

From you code it looks that you are initializing list only once when page
loads first time. So when page loads second time It want be able to find
variable list.

Just check following code.
protected void Page_Load(object sender, EventArgs e)
{
list = new ArrayList();
list.Add( "one" );
list.Add( "two" );
list.Add( "three" );
list.Add( "four" );
list.Add( "five" );
if( !Page.IsPostBack )
{

this.DataGrid1.DataSource = list;
this.DataGrid1.DataBind();
}
}


B
 
T

Teemu Keiski

That is perfectly normal since data source of a control is not stored over
postback since control already saves its state with ViewState (and also
control state in asp.net v2.0). So for performance reasons, it is not kept
by default (control itself is restored from viewstate)

You need to refetch the data to bind the control again (note: you certainly
can use state mechanisms in asp.net like session or cache to keep the data
available)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top