asp下拉列表没有得到正确的价值

时间:2012-11-21 13:54:17

标签: asp.net

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

下拉选择事件ALWAYS检索索引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

1 个答案:

答案 0 :(得分:0)

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

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

要停止此操作,您需要在代码周围添加if语句,以便在页面最初加载时(即不回发时)填充下拉列表

e.g。

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