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