views:

1088

answers:

3

I am creating a dropdown list in code for a gridview. I want to create an addhandler so I can have access to the selectedvalue. However, here (Rowdatabound) the add handler does not get fired off. How should I go about this?

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    ''//------------does not fire off add handler-----

    Dim deptvalue As String
    Dim ddlmgr As New DropDownList
    AddHandler ddlmgr.SelectedIndexChanged, AddressOf ddlmgr_SelectedIndexChanged
    ddlmgr.AutoPostBack = True

    ddlmgr.Items.Clear()
    ddlmgr.Items.Insert(0, "--Select a Manager--")
    ddlmgr.AppendDataBoundItems = True
    ddlmgr.DataTextField = "Name"
    ddlmgr.DataValueField = "number"
    ddlmgr.DataSource = SqlDataSource2
    ddlmgr.DataBind()

    ''//deptvalue = GridView1.Rows(i).Cells(0).Text
    deptvalue = e.Row.Cells(0).Text
    ddlmgr.Attributes.Add("onchange", "setDepart('" & deptvalue & "')")
    If e.Row.RowType <> DataControlRowType.Pager And e.Row.RowType <> DataControlRowType.Header And e.Row.RowType <> DataControlRowType.Footer Then
        e.Row.Cells(2).Controls.Add(ddlmgr)
    End If

End Sub
+1  A: 

This seems like a strange way to do things.

It looks like you are binding the same data on each rowdatabound event of the gridview. This is unneccesary if the drop-down items are the same in each row and are not impacted by any other information in the gridview row. Instead, on page load I would store the data in a dictionary (looks like name/value data) and then bind it to each dropdown list.

Also, I can't see why you are dynamically adding the dropdown list to each gridview row. Why not add the control and wire up the OnLoad event to bind the data in above. You can also wire up the OnSelectedIndexChanged event like you're trying to do above.

ScottE
ok, you are definitely on to something. Instead of dynamically doing this i just added a control. Just one more question...where would I add an onclick event to the dropdownlist? I need to set a value on client side
Eric
Nevermind, I got it.
Eric
A: 

When your ddlmgr's SelectedIndexChanged fires, a new postback is initiated. That means you are now working with a brand new instance of your page class. The old one where you had previously created the event handler is gone.

For the event to fire when you want it, you have to recreate the control for the new postback before state is restored, or the event handler won't be re-established.

Joel Coehoorn
A: 

+1 to Joel Coehoorn answer.

The place I usually do it is on Page_init event.

tekBlues