DataGrid DataSource is null on postback

  • Thread starter Thread starter Narshe
  • Start date Start date
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.
 
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();
}
}
 
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
 
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)
 
Back
Top