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
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.