0

我在页面加载时以这种方式填充我的下拉列表。(字符串生成器只是为了证明检索到了正确的列表项)

下拉选择事件总是检索索引 0,无论我从列表中选择什么项目,这让我相信我填充 dropdwonlist 的方式有问题,并且所选值始终是与该项目关联的值当下拉菜单出现在页面加载时,无论从下拉菜单中选择什么项目,它都是列表中的第一个。

 Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    'Dim sb As New StringBuilder()
    Using ctx As New dbentities()
        Try
            Dim query = (From c In ctx.my_aspnet_users Select c.name, c.id).ToList()

            ddlSiteUsers.DataSource = query
            ddlSiteUsers.DataTextField = "name"
            ddlSiteUsers.DataValueField = "id"
            ddlSiteUsers.DataBind()
            'For Each item As ListItem In ddlSiteUsers.Items
            '    sb.Append(item)
            '    sb.Append(",")
            '    sb.Append(item.Value)
            '    sb.Append(";" & vbCrLf)
            'Next
            'MsgBox(sb.ToString())
        Catch ex As Exception
            MsgBox(ex.StackTrace.ToString())
        End Try
    End Using
End Sub
4

1 回答 1

0

Page_Load()事件在页面最初加载时触发,并且在您回发页面时触发。

这意味着,在您的 click/indexchanged 事件触发之前,它会在Page_Load()您提交表单时重新运行您的代码。

要阻止这种情况,您需要if在代码周围添加一条语句,以便它仅在页面最初加载时(即不回发时)填充下拉列表

例如

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
  If Not Page.IsPostBack Then 
    'Dim sb As New StringBuilder()
    Using ctx As New dbentities()
      Try
        Dim query = (From c In ctx.my_aspnet_users Select c.name, c.id).ToList()

        ddlSiteUsers.DataSource = query
        ddlSiteUsers.DataTextField = "name"
        ddlSiteUsers.DataValueField = "id"
        ddlSiteUsers.DataBind()
        'For Each item As ListItem In ddlSiteUsers.Items
        '    sb.Append(item)
        '    sb.Append(",")
        '    sb.Append(item.Value)
        '    sb.Append(";" & vbCrLf)
        'Next
        'MsgBox(sb.ToString())
      Catch ex As Exception
        MsgBox(ex.StackTrace.ToString())
      End Try
    End Using
  End If
End Sub
于 2012-11-21T14:06:32.263 回答