Controls.Find 在特定的 if 语句中不起作用?

如何解决Controls.Find 在特定的 if 语句中不起作用?

我在使用 controls.find 时遇到问题,但找不到错误。

我正在使用不同的面板创建一个 loginform

面板创建如下:

 public Panel CreatePanel()
    {
        Panel login = new Panel();
        TextBox Login_UsernameTB = new TextBox();
        TextBox Login_PasswordTB = new TextBox();
        Label label1 = new Label();
        Label label2 = new Label();
        Label loginstatus = new Label();
        Button Login_Loginbtn = new Button();
        Button Login_Registerbtn = new Button();
        PictureBox Login_Logo = new PictureBox();
        PictureBox Login_ECard = new PictureBox();


        //creatingPanel
        login.Location = new Point(0,0);
        login.Name = "Login";
        login.Size = new Size(1000,400);


        //locations

        Login_ECard.Location = new Point(500,250);
        Login_ECard.SizeMode = PictureBoxSizeMode.StretchImage;
        Login_ECard.Image = PatientSimulator.Properties.Resources.Ecard;
        Login_ECard.Name = "Login_Ecard";

        Login_Logo.Location = new Point(148,12);
        Login_Logo.SizeMode = PictureBoxSizeMode.StretchImage;
        Login_Logo.Image = PatientSimulator.Properties.Resources.Logo;
        Login_Logo.Name = "Login_Logo";

        label1.Location = new Point(31,200);
        label1.Size = new Size(58,13);
        label1.Text = "Username:";
        label1.Name = "label1";

        label2.Location = new Point(31,244);
        label2.Size = new Size(56,13);
        label2.Text = "Password:";
        label2.Name = "label2";

        Login_UsernameTB.Location = new Point(148,197);
        Login_UsernameTB.Size = new Size(359,20);
        Login_UsernameTB.Text = "Testfirma1";
        Login_UsernameTB.Name = "Login_UsernameTB";

        Login_PasswordTB.Location = new Point(148,241);
        Login_PasswordTB.Size = new Size(359,20);
        Login_PasswordTB.Text = "Hallo1234#";
        Login_PasswordTB.PasswordChar = '*';
        Login_PasswordTB.Name = "Login_PasswordTB";

        Login_Loginbtn.Location = new Point(432,334);
        Login_Loginbtn.Size = new Size(75,23);
        Login_Loginbtn.Text = "Login";
        Login_Loginbtn.Click += Login_Loginbtn_Click;
        
        loginstatus.Location = new Point(323,360);
        loginstatus.Size = new Size(300,20);
        loginstatus.Text = "";
        loginstatus.Name = "loginstatus";
        
        Login_Registerbtn.Location = new Point(323,334);
        Login_Registerbtn.Size = new Size(75,23);
        Login_Registerbtn.Text = "Register";
        Login_Registerbtn.Click += Login_Registerbtn_Click;

        login.Controls.Add(Login_ECard);
        login.Controls.Add(Login_Logo);
        login.Controls.Add(label1);
        login.Controls.Add(label2);
        login.Controls.Add(Login_UsernameTB);
        login.Controls.Add(Login_PasswordTB);
        login.Controls.Add(Login_Loginbtn);
        login.Controls.Add(Login_Registerbtn);
        login.Controls.Add(loginstatus);

        return login;
    }

在 Form_load 中:

    Panel login = CreatePanel();
    login.Visible = true;
    Controls.Add(login);

当我启动应用程序时,一切都会显示出来。如果我在 systemstatus.text 中输入一些文本,则不会显示。

在检查输入的密码和用户名是否正确时,奇怪的事情发生了。

private void Login_Loginbtn_Click(object sender,EventArgs e)
    {
        Patient.DBAccess db = new Patient.DBAccess();
        Sha256 sha = new Sha256();
        string username = login.Controls.Find("Login_UsernameTB",true)[0].Text;
        string userpw = login.Controls.Find("Login_PasswordTB",true)[0].Text;            

        Patient.DatabaseRequestInterface.UserInterface user = new Patient.DatabaseRequestInterface.UserInterface();
        user.Username = username;
                   

        if (db.IsUserExisting(user)){
            user = db.ReadUserPassword(user);
            string salt = Encoding.ASCII.GetString(user.PasswordSalt);
            byte[] pw = sha.GetSha256(userpw,salt);

            if (pw.SequenceEqual(user.PasswordHash))
            {
                //Programm starten
                //token generieren
                Patient.DatabaseRequestInterface.UserInterface useri = db.ReadFullUser(user);

                UserAuthentificationToken = new UserInfo(useri.Username,useri.Uuid,DateTime.Now);
                LoginSuccessEvent?.Invoke(this,new EventArgs());
                
                login.Controls.Find("loginstatus",true)[0].Text = "Login successfull";

                this.Close();
            }
            else
            {
                MessageBox.Show("Login failed,Username and/or password incorrect");
            }
        
        }
        else
        {
            MessageBox.Show("Falscher User oder Passwort");
            //Controls.Find("Login_StatusL",true)[0].Text = "Login failed,Username and/or password incorrect!";
        }
    }

我使用 controls.find 的前 2 次它有效,我在相应的 TextBoxes 处得到用户输入的字符串。当我尝试更改 loginstatus 时,我得到一个 System.IndexOutOfRangeException。我对异常的解释是,没有找到 loginstatus。我不明白为什么。 (在 if 中也找不到其他 2 个元素) 有人可以帮忙吗?

controls.find("string",true)[0].Text = "XXX" 有效,我在应用程序的其他部分经常使用它

有什么想法吗? 提前致谢, 大卫

解决方法

您错过了代码中的 Name 属性并且 Controls.Find 严格执行 Name

    Login_UsernameTB.Name = "Login_UsernameTB";

所以你的代码应该是这样的:

    public Panel CreatePanel()
    {
        Panel login = new Panel();

        login.Size = new Size(900,900);

        TextBox Login_UsernameTB = new TextBox();
        Login_UsernameTB.Name = "Login_UsernameTB";
        Login_UsernameTB.Location = new Point(50,50);
        Login_UsernameTB.Text = "Username here";


        TextBox Login_PasswordTB = new TextBox();
        Login_PasswordTB.Name = "Login_PasswordTB";
        Login_PasswordTB.Location = new Point(150,50);
        Login_PasswordTB.Text = "password here";

        //stuff is asigned to TBs...

        Label loginstatus = new Label();
        loginstatus.Location = new Point(150,150);
        loginstatus.Size = new Size(300,20);
        loginstatus.Text = "";
        loginstatus.Name = "loginstatus";


        login.Controls.Add(Login_UsernameTB);
        login.Controls.Add(Login_PasswordTB);
        login.Controls.Add(loginstatus);

        return login;
    }

另外,login 应该是类级别的,但不在 Form_Load 中定义 像这样:

public partial class Form1 : Form
{

    Panel login;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender,EventArgs e)
    {
        login = CreatePanel();
        login.Visible = true;
        Controls.Add(login);
    }
    .....

我已经对其进行了测试并且运行良好。

我的测试代码是

using System;
using System.Drawing;
using System.Windows.Forms;

namespace SackOverflow
{
    public partial class Form1 : Form
    {

        Panel login;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender,EventArgs e)
        {
            login = CreatePanel();
            login.Visible = true;
            Controls.Add(login);
        }

        public Panel CreatePanel()
        {
            Panel login = new Panel();

            login.Size = new Size(900,900);

            TextBox Login_UsernameTB = new TextBox();
            Login_UsernameTB.Name = "Login_UsernameTB";
            Login_UsernameTB.Location = new Point(50,50);
            Login_UsernameTB.Text = "Username";


            TextBox Login_PasswordTB = new TextBox();
            Login_PasswordTB.Name = "Login_PasswordTB";
            Login_PasswordTB.Location = new Point(150,50);
            Login_PasswordTB.Text = "password";

            //stuff is asigned to TBs...

            Label loginstatus = new Label();
            loginstatus.Location = new Point(150,150);
            loginstatus.Size = new Size(300,20);
            loginstatus.Text = "";
            loginstatus.Name = "loginstatus";


            login.Controls.Add(Login_UsernameTB);
            login.Controls.Add(Login_PasswordTB);
            login.Controls.Add(loginstatus);

            return login;
        }

        private void button1_Click(object sender,EventArgs e)
        {
            if (true)
            {
                string username = login.Controls.Find("Login_UsernameTB",true)[0].Text;
                string userpw = login.Controls.Find("Login_PasswordTB",true)[0].Text;

                //UserInterface user = //some database stuff to get the password saved by the user

                if ("123" == userpw)
                {
                    login.Controls.Find("loginstatus",true)[0].Text = "Logging in";
                    Login();
                }
                else
                {
                    login.Controls.Find("loginstatus",true)[0].Text = "Error";
                }
            }
        }

        private void Login()
        {
            MessageBox.Show("Login");
        }
    }
}

结果是: 我收到消息框 MessageBox.Show("Login"); shown 并且 Loginstatusshown

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res