对于每个gridrow作为grid.row中的gridviewrow不处理最后一行

时间:2012-11-23 09:39:34

标签: asp.net sql gridview

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

到目前为止,我能够使用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

提前致谢!!!

1 个答案:

答案 0 :(得分:4)

为什么要将GridViewRows中的所有RowDataBound循环到每GridViewRow调用一次?

所以不是这个循环:

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或使用FindControl上的e.Row)