0

我正在尝试使用 asp.net 使用包含下拉列表的列填充网格视图。

到目前为止,我能够使用 SQL 表中的所有选项填充下拉列表,并且我还能够从 SQL 表中保存和读取选定的值,除了最后一行,它似乎忽略了它。

这是我的代码:

Protected Sub gridGenerators_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridGenerators.RowDataBound

    With e.Row
        If e.Row.RowType = DataControlRowType.DataRow Then

            'Populate all dropdown lists with options from SQL'
            Dim ddl = TryCast(.Cells(0).FindControl("ddlOnCallGroup"), DropDownList)

            ddl.DataSource = db.getSMSgroups()
            ddl.DataTextField = "SMS_Group"
            ddl.DataValueField = "id"
            ddl.DataBind()

            'And add a default when value is NULL'
            Dim l1 As New ListItem

            l1.Text = "-select-"
            l1.Value = ""

            ddl.Items.Add(l1)

            'Get the current setting from SQL (that user has permissions for)'
            Dim generators As String = Membership.GetUser().Comment
            Dim genDT As DataTable = db.locations(generators.Split(",".ToCharArray))

            'Iterate through settings and select value for each dropdownlist'
            For Each grdrow As GridViewRow In gridGenerators.Rows

                Dim drdList = TryCast(gridGenerators.Rows(grdrow.RowIndex).Cells(0).FindControl("ddlOnCallGroup"), DropDownList)

                drdList.SelectedValue = genDT.Rows(grdrow.RowIndex).Item("ID_SMS_Group").ToString

            Next

        End If
    End With

End Sub

提前致谢!!!

4

1 回答 1

4

你为什么要循环所有被调用的GridViewRows东西?RowDataBoundGridViewRow

所以代替这个循环:

For Each grdrow As GridViewRow In gridGenerators.Rows

    Dim drdList = TryCast(gridGenerators.Rows(grdrow.RowIndex).Cells(0).FindControl("ddlOnCallGroup"), DropDownList)
    drdList.SelectedValue = genDT.Rows(grdrow.RowIndex).Item("ID_SMS_Group").ToString

Next

只是这个:

Dim drdList = DirectCast(e.Row.FindControl("ddlOnCallGroup"), DropDownList)
drdList.SelectedValue = DirectCast(e.Row.DataItem, DataRowView).Item("ID_SMS_Group").ToString

请注意,我还更改了其他一些内容(例如访问DataItem或使用FindControlone.Row)

于 2012-11-23T09:57:07.010 回答