0

I am having a gridview and I am binding it only if it is Not POSTBACK, But I want to call the function RowDataBound when it is postback. How can I do that

 protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex == -1)
        {
        //Some logic
        }
    }

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LoadGridView();
        }
        else
        {
            gridview1_RowDataBound(null, null); // Object reference not set to an instance of an object 
        }
    }

How can I call it ?

hello temp11
  • 141
  • 4
  • 17
  • 1
    What's the purpose of calling RowDataBound? The problem is calling it not as a event handler but just as a function does not make a lot of sense. It is actually useful *only* while gridview is being data bound, otherwise you don't have access to event args, to data items, etc. Make sure calling it is really what you want – Andrei May 14 '15 at 17:49
  • Perhaps move your `if (!IsPostBack)` into the `gridview1_RowDataBound` event handler instead of in the `Page_Load` event handler. – dub stylee May 14 '15 at 17:49
  • @Andrei I get all the data for the grid view, but I want to add a textbox in the first row, which I tried few ways, but I am only able to do it by rowdatabound. So, if the index is -1 in the row databound, then i add the textbox. – hello temp11 May 14 '15 at 17:59
  • Well, I cannot tell I completely understand that, but a quick fix would be to replace `if (e.Row.RowIndex == -1)` with `if (e == null)`, which is causing your null reference. However again, I highly suspect you are doing this wrong way - rowdatabound should be called only when row is actually being data bound – Andrei May 14 '15 at 18:02
  • @Andrei Actually I am inserting a textbox in the first row, if `e.Row.RowIndex == -1` , then `e.Row.Cells[0].Controls.Add(Textbox1);` So I need to pass the gridview1 object. – hello temp11 May 14 '15 at 18:23
  • @hellotemp11, you need to understand what is the `e` you are using. Right now you are passing null there, and I am not completely sure if you can construct it on your own. Therefore i suggested null check – Andrei May 14 '15 at 18:26

1 Answers1

0

If you are creating any dynamic columns based on any conditions in Rowdatabound, then, if those conditions are not satisfied then make the grid not to have those dynamic columns. It solved my issue. Hope it will help someone.

pratham gn
  • 95
  • 1
  • 4
  • 14