我有一個下拉列表,我的網頁(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和一個ID爲「221」。
現在,我預填充的形式對個別訪問網站(如果可用)的信息 - 包括下拉列表,像這樣:
If getProspect IsNot Nothing Then
If getProspect.user_id Is Nothing Then
ddlProgram.SelectedValue = getProspect.Program
End If
End If
節目特性包含了許多的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
您是否在每次回傳中重新綁定? –
僅當頁面不是回發,拉入單個信息時,纔會爲程序列表的下拉列表綁定。 (包括他們選擇的程序)隨每次回發發生。然而,頁面通常是靜態的,不應該有真正的多次回發(除非某人出於任何原因決定刷新頁面)。 – davemackey
添加更多代碼以顯示您的頁面流 –