我试图制作两个将从数据库填充的下拉列表。出于某种原因,它说我的VB.net代码中的下拉列表没有声明。它应该从ASP代码中声明AcadYrDDL和TermDDL吗?
我是asp和vb.net的新手;需要一些帮助。而且,如果你们能指出我所犯的某些错误,那就太好了。
ASP:
<asp:DropDownList runat="server" id="AcadYrDDL" AppendDataBoundItems="true">
<asp:ListItem Text="option" Value=""/>
</asp:DropDownList>
<asp:DropDownList runat="server" id="TermDDL" AppendDataBoundItems="true">
<asp:ListItem Text="option" Value=""/>
</asp:DropDownList>
<asp:Button runat="server" type="button" id="viewButton" class="btn btn-default" value="View">
<span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>  View
</asp:Button>
</form>
VB.NET:
Imports System.Configuration
Imports System.IO
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Populate1()
Populate2()
End Sub
Public Sub Populate1()
Dim cmd As New SqlCommand("SELECT term FROM CADETCRSE", New SqlConnection(ConfigurationManager.AppSettings("ConnString")))
cmd.Connection.Open()
Dim ddlValues As SqlDataReader
ddlValues = cmd.ExecuteReader()
AcadYrDDL.DataSource = ddlValues
AcadYrDDL.DataValueField = ""
AcadYrDDL.DataTextField = "Acadyr"
AcadYrDDL.DataBind()
cmd.Connection.Close()
cmd.Connection.Dispose()
End Sub
Public Sub Populate2()
Dim cmd As New SqlCommand("SELECT AcadYr FROM CADETCRSE", New SqlConnection(ConfigurationManager.AppSettings("ConnString")))
cmd.Connection.Open()
Dim ddlValues As SqlDataReader
ddlValues = cmd.ExecuteReader()
TermDDL.DataSource = ddlValues
TermDDL.DataValueField = ""
TermDDL.DataTextField = "Current term"
TermDDL.DataBind()
cmd.Connection.Close()
cmd.Connection.Dispose()
End Sub
End Class
答案 0 :(得分:0)
DataValueField
和DataTextField
应该是数据库调用的字段。如果没有明确设置DataValueField
,请保留它,不要尝试将其设置为空字符串。您的最终代码应如下所示:
Public Sub Populate1()
Dim cmd As New SqlCommand("SELECT term FROM CADETCRSE", New SqlConnection(ConfigurationManager.AppSettings("ConnString")))
cmd.Connection.Open()
Dim ddlValues As SqlDataReader
ddlValues = cmd.ExecuteReader()
AcadYrDDL.DataSource = ddlValues
AcadYrDDL.DataTextField = "term" 'This is the field in your database call
AcadYrDDL.DataBind()
cmd.Connection.Close()
cmd.Connection.Dispose()
End Sub
Public Sub Populate2()
Dim cmd As New SqlCommand("SELECT AcadYr FROM CADETCRSE", New SqlConnection(ConfigurationManager.AppSettings("ConnString")))
cmd.Connection.Open()
Dim ddlValues As SqlDataReader
ddlValues = cmd.ExecuteReader()
TermDDL.DataSource = ddlValues
TermDDL.DataTextField = "AcadYr" 'As this is what you have returned in your
TermDDL.DataBind()
cmd.Connection.Close()
cmd.Connection.Dispose()
End Sub