views:

1597

answers:

4

First off, I realize most of this can also be done using ItemTemplates. If what I'm trying to do simply isn't possible, I will consider using them instead.

Here are the basics of my dilemma:

I have a GridView in the ASPX page that is loaded in the CodeBehind. Each row contains a couple of buttons that trigger the OnRowCommand event. When someone clicks the "Edit" button, I create a TextBox object and add it to the Controls collection of a particular cell.

This works fine.

The problem is, when the person clicks the "Save" button, OnRowCommand is triggered again but the cell is registering 0 items in the Controls collection. I'm pretty sure this is happening before a PostBack so I'm not sure why I can't access the TextBox control.

I checked after initially adding the TextBox and it shows 1 Control in the cell. Somewhere between loading the page with the textboxes and clicking the button, these controls have gone missing. Google wasn't much help. Any ideas?

A: 

You are dynamically creating textboxes so you have to re-bind your grid on each post back, give your textboxes and id (always the same) and re-attach any event handlers.

epitka
I didn't realize the controls were getting lost in the postback. Ended up just getting the values I wanted from the 'Request.Form' object. Still wish it was a bit easier to perpetuate the controls without creating TemplateFields for everything.
beardog
A: 

When the user clicks the edit button, you are in edit mode for the GridView. You need to set that up as well?

BenB
A: 

If you are creating controls on the fly, they will always disappear on postback, meaning that you will have to keep creating them on every cycle through.

I would personally suggest sticking with ItemTemplates and keeping yourself a little bit more free from the headaches that all of this can provide.

TheTXI
A: 

You can create an addhandler with a delegate when you create your button behind the code. the handler will fire before the rowcommand will.

 Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowCreated

Dim btnsave As New ImageButton
If e.Row.RowType <> DataControlRowType.Pager And e.Row.RowType <>  DataControlRowType.Header Then
    AddHandler btnedit.Click, AddressOf btnedit_Click
    GridView1.Rows(i).Cells(8).Controls.Add(btndel)
end if

end sub

Public Delegate Sub ImageClickEventHandler(ByVal sender As Object, ByVal e As ImageClickEventArgs)
Sub btnedit_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)

//do whatever you want here.
//possibly a redirect to the current page so nothing else fires

end sub
Eric
I appreciate the code example but I ended up with another solution. Thanks.
beardog