Giusepe Moreno
Giusepe Moreno

Reputation: 69

Gridview Dropdownlist binding

I am having a lot of trouble getting a dropdown to bind with data from my database with the appropriate departments.

This is what I have so far:

HTML:

<asp:GridView ID="gridDepartmentHistory" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">
            <Columns>
                <asp:TemplateField HeaderText="Department">
                    <ItemTemplate>
                        <asp:Label ID="lblDepartment" runat="server" Visible="true" Text='<%# Eval("Department")%>'></asp:Label>
                        <asp:DropDownList ID="ddlDepartment" runat="server">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Start Date" HeaderText="Start Date" />
                <asp:BoundField DataField="End Date" HeaderText="End Date" />
            </Columns>
        </asp:GridView>

Code behind:

    Protected Sub gridDepartmentHistory_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles gridDepartmentHistory.RowDataBound
    If (e.Row.RowType = DataControlRowType.DataRow) Then
        Dim ddlDepartment As DropDownList = CType(e.Row.FindControl("ddlDepartment"), DropDownList)
        Dim list As ICollection(Of Department) = Department.hrGetDepartmentList() 'Class method to fill a collection of items with the Department's Name and ID
        ddlDepartment.DataSource = list
        ddlDepartment.DataTextField = "Name"
        ddlDepartment.DataValueField = "ID"
        ddlDepartment.DataBind()
        Dim dept As String = CType(e.Row.FindControl("lblDepartment"), Label).Text
        ddlDepartment.Items.FindByText(dept).Selected = True
    End If
End Sub

When I run this it throws an exception saying:

Object reference not set to an instance of an object.

BTW: I am using this tutorial to help me through: http://www.aspsnippets.com/Articles/How-to-populate-DropDownList-in-GridView-in-ASPNet.aspx

Any help would be greatly appreciated! Thank you!

Upvotes: 0

Views: 183

Answers (2)

ALOK
ALOK

Reputation: 553

You simply need to retrieve dept id and store it in gridview as hidden (if you don't want to display it).

   Dim dept As String = CType(e.Row.FindControl("lblDepartmentId"), Label).Text
   ddlDepartment.SelectedValue = dept;

Hope it helps.

Upvotes: 1

Harval
Harval

Reputation: 76

Your problem is that you ara trying to find the contorl in the row but is inside a table cell.

Try this.

Dim cbo As DropDownList = CType(YourDGV.Rows(x).Cells(0).FindControl("ddlDepartment"), DropDownList)

Upvotes: 0

Related Questions