Gridview下拉列表绑定

时间:2014-11-28 13:21:48

标签: asp.net vb.net gridview

我在使用相应部门从数据库中绑定数据的下拉列表时遇到了很多麻烦。

这是我到目前为止所做的:

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>

代码背后:

    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

当我运行它时会抛出一个异常说:

  

对象引用未设置为对象的实例。

BTW:我正在使用本教程帮助我完成:http://www.aspsnippets.com/Articles/How-to-populate-DropDownList-in-GridView-in-ASPNet.aspx

任何帮助将不胜感激!谢谢!

2 个答案:

答案 0 :(得分:1)

您只需要检索dept id并将其作为隐藏存储在gridview中(如果您不想显示它)。

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

希望它有所帮助。

答案 1 :(得分:0)

您的问题是您正在尝试在行中找到控件但是在表格单元格内。

试试这个。

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