试图从C#转换为VB.net

时间:2014-04-25 16:19:01

标签: c# vb.net

我正在尝试将此C#代码更改为VB.net,并且遇到了用户名选择框没有填充成员资格用户列表的问题。 C#代码正确显示用户列表。

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class admin_change_change : System.Web.UI.Page
{

MembershipUserCollection users;

protected void Page_LoadComplete(object sender, EventArgs e)
{
    users = Membership.GetAllUsers();

    if (!IsPostBack)
    {
        UserName.DataSource = users;
        UserName.DataBind();
    }
}

protected void btnChange_Click(object sender, EventArgs e)
{
    MembershipUser userToChange = Membership.GetUser(UserName.SelectedItem.Value);

    if (userToChange != null)
    {
        userToChange.ChangePassword(userToChange.ResetPassword(), NewPassword.Text);
        Response.Redirect("/admin/");
    }
    else
    {
        message.Text = "Invalid Username or Password";
    }
}

protected void btnGoBack_Click(object sender, EventArgs e)
{
    Response.Redirect("/admin/");
}

}

VB.NET

Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls

Public Partial Class admin_change_change
Inherits System.Web.UI.Page

Private users As MembershipUserCollection

Protected Sub Page_LoadComplete(sender As Object, e As EventArgs)
    users = Membership.GetAllUsers()

    If Not IsPostBack Then
        UserName.DataSource = users
        UserName.DataBind()
    End If
End Sub

Protected Sub btnChange_Click(sender As Object, e As EventArgs)
    Dim userToChange As MembershipUser = Membership.GetUser(UserName.SelectedItem.Value)

    If userToChange IsNot Nothing Then
        userToChange.ChangePassword(userToChange.ResetPassword(), NewPassword.Text)
        Response.Redirect("/admin/")
    Else
        message.Text = "Invalid Username or Password"
    End If
End Sub

Protected Sub btnGoBack_Click(sender As Object, e As EventArgs)
    Response.Redirect("/admin/")
End Sub

End Class

2 个答案:

答案 0 :(得分:1)

您的事件处理程序在其末尾缺少Handles Me.LoadComplete

Protected Sub Page_LoadComplete(sender As Object, e As EventArgs) Handles Me.LoadComplete
    users = Membership.GetAllUsers()

    If Not IsPostBack Then
        UserName.DataSource = users
        UserName.DataBind()
    End If
End Sub

答案 1 :(得分:1)

默认情况下,ASP.Net VB中的AutoEventWireup为false。因此,您需要明确地附加像roryap建议的事件。

<%@ Page AutoEventWireup="false" %>

但是,如果您不想手动附加,则可以使AutoEventWireup="true"成为ASP.net C#中的默认值。

确保 Page_LoadComplete 应重命名为 Page_Load ,这是一个展位事件名称。

Protected Sub Page_Load(sender As Object, e As EventArgs)
    If Not IsPostBack Then
        Dim users = Membership.GetAllUsers()
        UserName.DataSource = users
        UserName.DataBind()
    End If
End Sub

此外,用户应位于 if语句内,如果其值未在页面的其余部分使用,以避免从DataBase中检索不必要的数据。

Here是免费的VB转C#代码转换器。