如果找不到字符串,请在文本框中重新输入字符串

时间:2017-03-15 16:49:48

标签: c# loops textbox

如果字符串不匹配,如何在文本框中重新输入字符串?

我正在尝试的代码但是它停留在循环中并且不允许我在文本框中再次输入字符串。

任何人都可以指导我如何做到这一点

代码是:

public void userpass()
        {
            int us = 0; //for user pass
            string readText2 = File.ReadAllText(pathuser);
            using (StreamReader sr2 = new StreamReader(pathuser))
            {

                string usernam = username.Text;
                string line;
                string[] lines = new String[500];

                while ((line = sr2.ReadLine()) != null )
                {
                    lines[us] = line;


                    if (lines[us] == usernam && usernam != "")
                    {
                        check = 1;
                        MessageBox.Show(usernam);
                        Form2 f2 = new Form2();
                        this.Hide();
                        break;
                    }
                    us++;
                }

                if (lines[us-1] != usernam && usernam != null)
                {
                    this.DialogResult = DialogResult.None;
                    DialogResult result = new DialogResult();
                    result = MessageBox.Show("Invalid Username or Password?", "Retry", MessageBoxButtons.OK);
                    if (result == DialogResult.OK)
                    {

                        username.Clear();


                    }
                }
            }

1 个答案:

答案 0 :(得分:0)

好的,所以我认为你的问题主要是检查文件中是否存在该值。您可以使用此功能检查是否存在,然后您可以执行所需操作:

public bool findValueInFile(string filePath, string value)
{
    //Get all lines from the txt file
    string[] lines = File.ReadAllLines(filePath);            

    //Go thru all the lines
    foreach(string line in lines)
    {
        //If we find the line we're looking for
        if (line.Equals(value))
        {
            return true;
        }
    }

    //If we haven't found anything return false
    return false;
}

根据回复调用此函数后,您可以显示消息框或执行其他操作:

if(findValueInFile(yourPath, yourValue))
{
    // We found the value
}
else
{
    // We didn't find the value
}