我的页面(ddlProgram)上有一个下拉列表,通过数据库查询填充,如下所示:
Using dbContext as IRFEntities = New IRFEntities
Dim getPrograms = (From p in dbContext.IRF_Program _
Order By p.name _
Select p)
ddlProgram.DataSource = getPrograms
ddlProgram.DataTextField = "name"
ddlProgram.DataValueField = "id"
ddl.Program.DataBind()
End Using
因此,例如,可能有一个“教育”的 DataTextField 和一个“221”的 ID。
现在,我使用有关访问该站点的个人的信息(如果有)预先填充表单 - 包括如下所示的下拉列表:
If getProspect IsNot Nothing Then
If getProspect.user_id Is Nothing Then
ddlProgram.SelectedValue = getProspect.Program
End If
End If
Program 属性包含一个与 Program 的 ID 匹配的数字。因此,例如,这个人可能有一个“221”计划,它与上述教育的“221”相匹配。
目前,应用程序成功地将 DropDownList (ddlProgram) 的 SelectedValue 设置为“221”,但 DDL 的 SelectedItem 保持不变(例如,如果它最初是“History”,在预填充后 ID 为“1”,则它是“历史”,ID 为“221”)。
我想要发生的事情是将 SelectedItem 更新为与 SelectedValue 对应的项目。因此,最后,如果个人在预填充表单时选择了“教育”的“221”,他们会将教育视为所选项目,并且所选值将被正确设置,而现在表单显示错误的 SelectedItem但在幕后拥有正确的 SelectedValue。
下面是来自 Page_Load 事件的代码流的更完整概念:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack = False Then
' If prospect is coming from unique url
Dim prospect_url As String = Page.RouteData.Values("value")
' Save prospect_url into session variable
Session("prospect_url") = prospect_url
Using dbContext As IRFEntities = New IRFEntities
' Prepopulate the programs dropdown.
Dim getPrograms = (From p In dbContext.IRF_Program _
Order By p.name _
Select p)
ddlProgram.DataSource = getPrograms
ddlProgram.DataTextField = "name"
ddlProgram.DataValueField = "id"
ddlProgram.DataBind()
End Using
Using dbContext As IRFEntities = New IRFEntities
' Prepopulate the states dropdown.
Dim getStates = (From p In dbContext.IRF_States _
Order By p.name _
Select p)
ddlState.DataSource = getStates
ddlState.DataTextField = "name"
ddlState.DataValueField = "id"
ddlState.DataBind()
End Using
Using dbContext As IRFEntities = New IRFEntities
' Grab info. about prospect based on unique url.
Dim getProspect = (From p In dbContext.IRF_Prospects _
Where p.url = prospect_url _
Select p).FirstOrDefault
' If they have a record...
If getProspect IsNot Nothing Then
If getProspect.user_id Is Nothing Then
' Prepopulate the form with their information.
' These must have a value, so we need to make sure that no column is null in the database.
ddlProgram.SelectedValue = getProspect.program
txtFirst.Text = getProspect.first_name
txtLast.Text = getProspect.last_name
txtAddress.Text = getProspect.address
txtCity.Text = getProspect.city
ddlState.SelectedValue = getProspect.state
txtZip.Text = getProspect.zip
txtPhone.Text = getProspect.phone
txtEmail.Text = getProspect.email_address
txtYearEnrolling.Text = getProspect.enrolling_in
Else
' Redirect them to login.
Response.Redirect("login.aspx")
End If
End If
End Using
End If
End Sub