object reference not set to an instance of an object - when gridview has paging? RRS feed

  • Question

  • User2091173246 posted


    I have a gridview with paging option

    protected void gwActivity_PageIndexChanging(object sender, GridViewPageEventArgs e)
    gwActivity.PageIndex = e.NewPageIndex;


    I rebound the gridview when a new page is set.

    however there is an issue with Rowcommand when paging.

    protected void gwActivity_RowCommand(object sender, GridViewCommandEventArgs e)


    GridViewRow row = ((e.CommandSource as Control).NamingContainer as GridViewRow);
    txtActivity.Text = row.Cells[2].Text;
    ddlStatus.SelectedValue = row.Cells[4].Text;}


    object reference not set to an instance of an object

    i do not know what to do here?


    Wednesday, April 4, 2018 7:12 AM

All replies

  • User-1724331924 posted

    Hi Skwizzy,

    From your post, it is not clear that in which line/section the exception happens.

    But I can say you that this exception happens due to "null reference" which means, "row" can be null and trying to access the same.

    Try the following way to get row:

    int index = Convert.ToInt32(e.CommandArgument);
    // Retrieve the row that contains the button clicked 
    // by the user from the Rows collection.
    GridViewRow row = gwActivity.Rows[index];

    If the exception happens for another object, please let us know.



    Wednesday, April 4, 2018 7:48 AM
  • User2091173246 posted

    Hi, Sorry, the exection happend on:

    row.Cells[2].Text = 'row.Cells[2].Text' threw an exception of type 'System.NullReferenceException'

    However your example work BUT when i press "SELECT" in my gridview i gett an error:

    Index was out of range. Must be non-negative and less than the size of the collection.

    The only one that works is INDEX: 1 ? but i have like 20+ rows and there will be more in my gridview

    Wednesday, April 4, 2018 7:58 AM
  • User-1838255255 posted

    Hi Skwizzy,

    According to your description, as far as i know, this issue maybe caused by the can not get the row or the cells in the row is null, i suggest you add a break point to check the row and cells value, you could check this tutorial about how to debug code:


    Best Regards,

    Eric Du  

    Tuesday, April 10, 2018 9:21 AM