如何从DataSet填充DropDown列表?

时间:2014-03-28 04:45:13

标签: vb.net

我正在尝试使用数据集中返回的存储过程的结果填充vb.net中的ASP下拉列表。我想知道是否有人知道vb.net代码填充下拉列表?

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load

    Dim connString As String = "Server=MYCOMPUTER\SQLEXPRESS;Database=scales;Trusted_Connection=True"
    Dim myConn As New SqlConnection(connString)
    myConn.Open()
    Dim da As New SqlDataAdapter("select scaleName from scales", myConn)
    Dim dt As New DataTable
    da.Fill(dt)

    ComboBox1.DisplayMember = "scaleName"

    ComboBox1.DataSource = dt
    myConn.Close()

2 个答案:

答案 0 :(得分:1)

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
             IF Not IsPostback then
               PopulateDropdown()
             End IF
End Sub

Private Sub PopulateDropDown()
      Dim connString As String = "Server=MYCOMPUTER\SQLEXPRESS;Database=scales;Trusted_Connection=True"
      Dim myConn As New SqlConnection(connString)
      myConn.Open()
      Dim da As New SqlDataAdapter("select ScaleId, scaleName from scales", myConn)
      Dim dt As New DataTable
      da.Fill(dt)

          Me.ComboBox1.DataTextField = "scaleName "
          Me.ComboBox1.DataValueField = "ScaleId"
          Me.ComboBox1.DataSource = dt
          Me.ComboBox1.DataSourceID = String.Empty
          Me.ComboBox1.DataBind()

     myConn.Close()
End Sub

答案 1 :(得分:0)

为了在DropDownList控件中显示数据,您可以使用以下代码。要使用存储过程的结果,需要创建SELECT命令:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        Dim dt As New DataTable
        Dim connString As String = "Server=MYCOMPUTER\SQLEXPRESS;Database=scales;Trusted_Connection=True"
        Using myConn As New SqlConnection(connString)
            myConn.Open()
            Using cmd = myConn.CreateCommand()
                cmd.CommandType = CommandType.StoredProcedure
                cmd.CommandText = "dbo.uspMyStoredProc"
                cmd.Parameters.AddWithValue("@MyInputParam", 123)
                Using da As New SqlDataAdapter(cmd)
                    da.Fill(dt)
                End Using
            End Using
        End Using
        ComboBox1.DisplayMember = "scaleName"
        ComboBox1.DataSource = dt
        ComboBox1.DataBind()
    End If
    ' ...
End Sub

我调整了以下内容:

  • 通常您只需要在初始请求中绑定数据。因此,开头的if语句将检查IsPostBack属性。
  • 为了可靠地关闭和处理连接和数据数据,我添加了一些using语句。
  • 为了访问存储过程,我创建了一个SqlCommand并将CommandType设置为StoredProcedureCommandText设置为存储过程的名称。在示例中,我还添加了一个名为MyInputParam的参数,该参数将发送到存储过程。