0

我有一個asp.net Visual Basic網站,我正在使用存儲過程來獲取值以填充下拉列表。visual basic asp.net dropDownList未填充值

但是,我有兩個問題。如果我將方法填充到頁面加載事件的If Not IsPostBack語句中的下拉列表中,則整個列表中將填充表示「System.Data.DataViewRow」而不是實際值的項目。如果我把它放在這個'if'聲明之外,但仍然在我的頁面加載事件中,我會得到正確的值,但無論我選擇什麼,當我離開下拉菜單時,它將恢復到頂部項目而不是所選項目。

我在做什麼錯?

編輯:我現在已經按照Nic的建議添加了DataTextField,並將該方法放入我的'If Not IsPostBack'事件中,正如Lee Bailey所建議的那樣。然而,我的下拉菜單仍然顯示所有的值爲「System.Data.DataViewRow」,所以我不知道李的解決方案是否有效!關於展示價值的任何其他想法!我已在下面更新了我的代碼以反映這些更改。

在Visual Basic:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
    If Not IsPostBack Then 
     bodyPanel.Visible = False 
     drpRegion_fill() 
    End If 
End Sub 

Protected Sub drpRegion_fill() 
    Dim sqlConn As SqlConnection 
    sqlConn = New SqlConnection 
    sqlConn.ConnectionString = ConfigurationManager.ConnectionStrings("ConnString").ConnectionString 
    Dim drpRegionCmd As SqlCommand 
    drpRegionCmd = New SqlCommand("getRegionName", sqlConn) 
    drpRegionCmd.CommandType = CommandType.StoredProcedure 

    Dim drpRegionAdp As SqlDataAdapter 
    drpRegionAdp = New SqlDataAdapter(drpRegionCmd) 
    Dim drpRegionDs As DataSet 
    drpRegionDs = New DataSet 

    sqlConn.Open() 
    drpRegionAdp.Fill(drpRegionDs) 

    With drpRegion 
     .DataSource = drpRegionDs 
     .DataBind() 
     .DataValueField = "regionName" 
     .DataTextField = "regionName" 
     .SelectedIndex = 0 
    End With 

    sqlConn.Close() 
End Sub 

的標記:

<asp:Panel ID="panelRegion" runat="server" Height="160px" Width="71%" CssClass="inlineBlock"> 
<h2>Region:</h2> 
<asp:dropDownList runat="server" AutoPostBack="true" ID="drpRegion" /> 
</asp:Panel> 

SQL過程返回與 'regionID' 作爲第1列,和 'regionName' 作爲COLUMN2兩列數據集。

我已經花了大約兩天的時間來嘗試各種各樣的事情並閱讀所有的書籍!我從來沒有在C#中遇到過這個問題,當我執行相同的操作時,我無法爲我的生活想到我在VB中錯過了什麼......

+1

設置DataTextField是否有所作爲? –

+0

你在哪裏設置DataTextField? – Ric

回答

2

看起來好像您正在設置DataTextField你的DropDownList的屬性:

With drpRegion 
     .DataSource = drpRegionDs 
     .DataValueField = "regionName" 
     .DataTextField = "fieldToDisplayAsText" 
     .SelectedIndex = 0 
     .DataBind() 
End With 

來源: MSDN DataTextField

+0

謝謝 - 現在測試 – Elatesummer

+0

我試過這個,但它沒有解決我的問題,編輯我原來的問題,添加更新的代碼。 – Elatesummer

+0

您是否將DataTextField屬性設置爲正確的值,即DataTable中的列名? – Ric

1

它恢復到原來的價值,因爲你是一個回發後重新綁定值的下拉。因爲您將AutoPostBack屬性設置爲true,所以更改選定的項目會觸發回發。只有當它不是回發時,我纔會調用drpRegion_fill()。設置DataTextField爲Ric提到應該解決有關'System.Data.DataViewRow'的問題

+0

謝謝 - 我已將此內容移至「If Not IsPostBack」部分,現在將進行測試 – Elatesummer

+0

我已將電話移至page_load事件的'If Not IsPostBack'部分,但我不確定是否需要它的工作,因爲我現在有問題的所有項目顯示爲System.Data.DataViewRow - 儘管我也添加了由Ric推薦的DataTextField屬性?試試看,然後測試......謝謝! – Elatesummer

+0

現在,我已經遵循了Ric的所有建議 - 非常感謝你!我只能標記一個作爲答案,雖然:/ – Elatesummer