Reputation: 215
I am trying to populate a gridview with columns that contain a dropdownlist using asp.net.
So far I am able to populate the dropdownlist with all options from a SQL table and I am also able to save and read the selected values from a SQL table except for the very last row it just seems to ignore it.
Heres my code:
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
Thanks in advance!!!
Upvotes: 0
Views: 970
Reputation: 460148
Why are you looping all GridViewRows
in RowDataBound
which is called for every GridViewRow
anyway?
So instead of this loop:
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
just this:
Dim drdList = DirectCast(e.Row.FindControl("ddlOnCallGroup"), DropDownList)
drdList.SelectedValue = DirectCast(e.Row.DataItem, DataRowView).Item("ID_SMS_Group").ToString
Note that i've also changed some other things(like accessing the DataItem
or using FindControl
on e.Row)
Upvotes: 4