Handling the SelectedIndexedChanged event of a DropDownList in a GridView in ASP.NET 2.0

Say you had a GridView with a dropdownlist like this:

<asp:GridView ID="testGridView" runat="server">
        <asp:BoundField DataField="TestField" />
                <asp:DropDownList ID="TestDropDownList" runat="server" AutoPostBack="true">
                    <asp:ListItem Value="1">Item 1</asp:ListItem>
                    <asp:ListItem Value="2">Item 2</asp:ListItem>

And you set it’s datasource in the page load event like this:

Protected Sub Page_Load(ByVal sender AsObject, ByVal e As System.EventArgs) HandlesMe.Load
    If Not Me.IsPostBack Then
        Dim testTable As New DataTable
        Dim testColumn As New DataColumn
        testColumn.ColumnName = "TestField"
        testColumn.DataType = GetType(String)
        Dim testRow As DataRow
        testRow = testTable.NewRow
        testRow.Item("TestField") = "Item 1"
        testRow = testTable.NewRow
        testRow.Item("TestField") = "Item 2"
        testRow = testTable.NewRow
        testRow.Item("TestField") = "Item 3"
        Me.testGridView.DataSource = testTable
    End If
End Sub

Now say you wanted to add an event handler of the drop down list in the GridView. You may be tempted to try using the AddHandler method in the RowDataBound event of the GridView like this:

Protected Sub testGridView_RowDataBound(ByVal sender AsObject, ByVal e As GridViewRowEventArgs) Handles testGridView.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim testDropDownList As DropDownList = CType(e.Row.FindControl("TestDropDownList"),             DropDownList)
        AddHandler testDropDownList.SelectedIndexChanged, AddressOf TestDropDownList_SelectedIndexChanged
    End If
End Sub

Protected Sub TestDropDownList_SelectedIndexChanged(ByVal sender AsObject, ByVal e As EventArgs)
    Dim bla As Integer = 3
End Sub

But you will unfortunately discover that this does not work as a break point set on Dim bla is never reached. You have to tie the event handler directly in the aspx like this:

<asp:DropDownListID="TestDropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="TestDropDownList_SelectedIndexChanged">


Popular posts from this blog

Show/Hide formatting text in MS Word 2010

Microsoft.ApplicationBlocks. ExceptionManagement The event source x does not exist error

ASP.NET 2.0 DropDownList EnableViewState