ASP.NET VB列表框DataBind不起作用

时间:2013-04-22 21:42:01

标签: asp.net vb.net asp.net-membership

在我的用户控件中,我有一个用于创建新成员资格用户的文本框。每个列表框都有一个数据源设置为membership.getallusers()以填充列表框。更改列表框索引后,它会填充文本框以允许编辑。我想要完成的是:让每个用户列表框刷新以显示创建的新用户。即使我在成功创建用户后调用databind(),它也不会更新。在表单加载中,我检查listbox.items.count < 1是否为databind(),然后调用Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If ListBox3.Items.Count < 1 Then For Each item As MembershipUser In Membership.GetAllUsers(0, Membership.GetAllUsers.Count + 1, Membership.GetAllUsers.Count) ListBox3.Items.Add(item.UserName) Next Label1.Text = ListBox3.Items.Count username = ListBox3.Items(0).ToString Else ListBox1.DataBind() ListBox3.DataBind() End If user = Membership.GetUser ListBox1.DataSource = Membership.GetAllUsers ListBox1.DataBind() ListBox2.DataSource = Roles.GetAllRoles ListBox2.DataBind() ' ListBox3.DataSource = Membership.GetAllUsers 'ListBox3.DataBind() End Sub Protected Sub ListBox3_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox3.SelectedIndexChanged txtUsername.Text = user.UserName txtEmail.Text = user.Email txtQuestion.Text = user.PasswordQuestion End Sub Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Try'Creates a new user Dim status As System.Web.Security.MembershipCreateStatus Membership.CreateUser(txtUsername.Text, txtPassword.Text, txtEmail.Text, txtQuestion.Text, txtAnswer.Text, True, status) Label1.Text = "User " & txtUsername.Text & " was created" 'ListBox3.Items.Clear() ListBox1.DataBind() 'ListBox3.DataBind() Catch ex As Exception Label1.Text = "Error:" & ex.Message End Try End Sub ,它可以正常工作。有什么想法吗?

{{1}}

1 个答案:

答案 0 :(得分:1)

在执行数据绑定之前,需要再次设置数据源,如下所示:

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Try'Creates a new user
        Dim status As System.Web.Security.MembershipCreateStatus
        Membership.CreateUser(txtUsername.Text, txtPassword.Text, txtEmail.Text, txtQuestion.Text, txtAnswer.Text, True, status)
        Label1.Text = "User " & txtUsername.Text & " was created"
        'ListBox3.Items.Clear()
        ListBox1.DataSource = Membership.GetAllUsers()  ' Necessary because the DB has changed
        ListBox1.DataBind()
        'ListBox3.DataBind()
    Catch ex As Exception
        Label1.Text = "Error:" & ex.Message
    End Try
End Sub

当您调用数据绑定时,您可能会认为这是Listbox将您作为数据源调用的方法调用的时刻,但事实并非如此。分配数据源的那一刻,将检索数据。当您实际调用Databind方法时,Listbox将创建必要的内部控件