You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# ListBox用户名唯一性校验问题:重复输入未触发错误提示

解决ListBox用户名唯一性判断失效的问题

嘿,刚接触C#就遇到这种属性误用的坑太正常啦,我来帮你搞定!

问题根源

你现在的代码里犯了一个关键错误:用错了ListBox的属性。ContainsFocus是用来判断ListBox当前是否获得了输入焦点(比如用户点击了ListBox让它处于激活状态),它是一个布尔值,你把它和输入的用户名字符串做Equals比较,布尔值和字符串永远不可能相等,所以find变量永远是false,错误提示自然不会显示。

修正后的代码

下面是直接可以用的修正版本,我帮你简化了逻辑:

private void txt_Username_TextChanged(object sender, EventArgs e) {
    // 检查ListBox的项集合中是否包含输入的用户名
    bool isUsernameExists = lb_Form1_ListUsers.Items.Contains(txt_Username.Text);
    // 直接根据判断结果设置错误提示的可见性
    lbl_Form1_UniqueError.Visible = isUsernameExists;
}

额外说明(如果以后用自定义对象)

如果你的ListBox里绑定的不是纯字符串,而是自定义的用户对象(比如有Username属性的User类),那上面的Contains方法就不适用了,需要遍历每个项来比较:

private void txt_Username_TextChanged(object sender, EventArgs e) {
    bool isUsernameExists = false;
    string inputUsername = txt_Username.Text.Trim(); // 建议去掉首尾空格,避免误判
    
    foreach (var item in lb_Form1_ListUsers.Items) {
        // 把项转换成你的用户对象类型
        User currentUser = item as User;
        if (currentUser != null && currentUser.Username == inputUsername) {
            isUsernameExists = true;
            break; // 找到匹配项就跳出循环,提升效率
        }
    }
    
    lbl_Form1_UniqueError.Visible = isUsernameExists;
}

这样修改后,当你输入ListBox中已有的用户名时,错误提示就会正常显示啦~

内容的提问来源于stack exchange,提问作者user12515401

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 17:57:45