DataBind() on Postback

Please junior developers don't Databind() your GridView on Postback.  You only need to databind your GridView once, when the page is first loaded (and anytime the data changes).  However, if you are lazy then you will DataBind on every postback forcing the GridView to go to the data source every postback and making your page slow. 

Your junior code:

protected void Page_Load(object sender, EventArgs e)
{
    ERSGridView1.DataBind();
}

My code:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
        ERSGridView1.DataBind();
}

But, But...

Yes DataItem will not be accessible on Postback, so this code will not work:

protected void ERSGridView1_SelectedIndexChanged(object sender, EventArgs e)
{
   object myData = ERSGridView1.SelectedRow.DataItem;
}
You will have to do this:
protected void ERSGridView1_SelectedIndexChanged(object sender, EventArgs e)
{
   Int32 primaryKey = (Int32)ERSGridView1.DataKeys[ERSGridView1.SelectedIndex].Value;
   // Fetch Object From Data Source
}

I know, you have to fetch the object if the row is selected, however this is much better performance and more scaliable then fetching the all the objects on every post back.  Yes, the gridview will display all the rows if you don't DataBind, that is becuase it saves that information in ViewState and repopulates the row.

Two years ago this might not be as important.  However when you start Ajaxing your page (with Microsoft's ATLAS Extenders) there ends up being a lot more PostBacks that don't involve data changes.

{6230289B-5BEE-409e-932A-2F01FA407A92}

 

 

Comments

Popular posts from this blog

Yet once more into the breech (of altered programming logic)

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

How to convert SVG data to a Png Image file Using InkScape