Eric
Eric

Reputation: 8088

Dropdown list and gridview row-index/selectedvalue issue

I have a gridview with a dropdown list that was created programmatcially. I want to have
access to the selected value and to that row's Id. I have the dropdownlist created in Gridview_RowDataBound and I am able to use the text in the cell but my addHandler is never fired. Where do I give it the Add handler. I believe I can assign it the addhandler in RowCreated but how would I be able to set up the add handler if the button is created in rowdatabound?

Dim deptvalue As String
    Dim i As Integer = 0

    Dim ddlmgr As New DropDownList
    ddlmgr.AutoPostBack = True
    AddHandler ddlmgr.SelectedIndexChanged, AddressOf ddlmgr_SelectedIndexChanged
    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 = 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

    If e.Row.RowType <> DataControlRowType.Pager And e.Row.RowType <> DataControlRowType.Footer Then
        e.Row.Cells(0).Style.Add("display", "none")
    End If

It fits best in Rowdata bound because my dropdownlist items don't duplicate but I need to be able to use the addhandler I created.

Upvotes: 0

Views: 7545

Answers (2)

Eric
Eric

Reputation: 8088

Instead of creating the dropdown dynamically i added the control to the gridview. By doing that I had access to the Selected value. Then I Set the value of the hidden value by adding an onchange attribute to the dropdown list that set the hidden value to the text in my hidden field. The following is in Gridview_RowDatabound:

 For i As Integer = 0 To GridView1.Rows.Count - 1

        Dim ddl As DropDownList = GridView1.Rows(i).FindControl("ddlmgr")
        Dim deptvalue As String = GridView1.Rows(i).Cells(0).Text

        ddl.Attributes.Add("onchange", "setDepart('" & deptvalue & "')")
    Next

Upvotes: 1

Rob
Rob

Reputation: 3066

Instead of using the cell text, why not just use e.item.DataItem from rowDatabound to get the actual value?

Upvotes: 0

Related Questions