Visual Basic注册登录页面开发问题求助
VB注册登录页面问题修复
原代码核心问题
- 注册逻辑中,局部变量
UN和PW未从文本框读取输入值,导致始终为空,既无法正确存储账号,还会错误判定空用户名重复 - 检测到用户名重复后未终止注册流程,仍会执行存储操作
- 冗余的
count1计数器,用户名与密码是一一对应的,单个计数器即可,避免索引不同步 - 登录逻辑未读取当前输入的账号密码,且用字符串连接符
&替代了逻辑与运算符AndAlso - 全局共享的
UN、PW变量无实际作用,属于冗余代码
修正后的完整代码
Public Class WebForm1 Inherits System.Web.UI.Page Public Shared Username(50) As String Public Shared Password(50) As String Public Shared userCount As Integer = 0 Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim inputUN As String = TextBox1.Text.Trim() Dim inputPW As String = TextBox2.Text.Trim() ' 校验用户名非空 If String.IsNullOrEmpty(inputUN) Then MsgBox("请输入注册用户名", vbExclamation, "错误") Exit Sub End If ' 校验密码非空 If String.IsNullOrEmpty(inputPW) Then MsgBox("请输入注册密码", vbExclamation, "错误") Exit Sub End If ' 检查用户名是否重复 For i As Integer = 0 To userCount - 1 If Username(i) = inputUN Then MsgBox("该用户名已被使用!请输入新的用户名", vbExclamation, "错误") Exit Sub ' 找到重复后直接终止注册流程 End If Next ' 存储账号密码 Username(userCount) = inputUN Password(userCount) = inputPW userCount += 1 MsgBox("注册成功!", vbInformation, "提示") End Sub Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim inputUN As String = TextBox1.Text.Trim() Dim inputPW As String = TextBox2.Text.Trim() Dim isAuthenticated As Boolean = False ' 遍历验证账号密码 For i As Integer = 0 To userCount - 1 If Username(i) = inputUN AndAlso Password(i) = inputPW Then isAuthenticated = True Exit For ' 找到匹配项后终止循环,提升效率 End If Next If isAuthenticated Then MsgBox("Access Granted") Else MsgBox("用户名或密码错误", vbCritical, "登录失败") End If End Sub End Class
关键修正说明
- 读取输入时添加
Trim()去除首尾空格,避免无效的空白账号 - 检测到重复用户名后立即终止注册,防止错误存储
- 用单个
userCount维护数组索引,确保用户名和密码一一对应 - 登录时使用
AndAlso做逻辑判断(短路求值,提升性能),同时添加登录失败提示 - 删除冗余的全局变量,简化代码结构
内容的提问来源于stack exchange,提问作者Braden Tate
相关产品推荐
相关产品推荐

