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">
    <Columns>
        <asp:BoundField DataField="TestField" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:DropDownList ID="TestDropDownList" runat="server" AutoPostBack="true">
                    <asp:ListItem Value="1">Item 1</asp:ListItem>
                    <asp:ListItem Value="2">Item 2</asp:ListItem>
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

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)
        testTable.Columns.Add(testColumn)
        Dim testRow As DataRow
        testRow = testTable.NewRow
        testRow.Item("TestField") = "Item 1"
        testTable.Rows.Add(testRow)
        testRow = testTable.NewRow
        testRow.Item("TestField") = "Item 2"
        testTable.Rows.Add(testRow)
        testRow = testTable.NewRow
        testRow.Item("TestField") = "Item 3"
        testTable.Rows.Add(testRow)
        Me.testGridView.DataSource = testTable
        Me.testGridView.DataBind()
    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">

Comments

Popular posts from this blog

ToMethodObject Refactoring

How to unlock a file in Team Foundation Server(TFS)

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