Как проверить, была ли введена строка? - PullRequest
1 голос
/ 31 мая 2019

есть текстовое поле и, введя имя в нем, оно проверяет, есть ли такое имя в словаре, если оно есть, отображает сообщение и просит переписать имя, но у меня есть нажатие клавиши, которое пропускает все русские буквыи после вывода сообщения соответствия имени игра продолжается. Вот код с нажатием клавиши и кнопка с проверкой, есть ли такое имя или нет: Вопрос в том, как обойти нажатие клавиши с повторяющимся именем?

private void Button5_Click(object sender, EventArgs e)
    {
        var dict = new Dictionary<string, int>(); // where will the data be imported from the file
        using (var stream = new StreamReader(@"C:\Users\HP\Desktop\photo\results.txt")) // open file
        {
            // auxiliary elements
            var line = "";
            string[] param;
            // go through all the lines
            while ((line = stream.ReadLine()) != null)
            {
                param = line.Split(' '); // Break line
                dict.Add(param[0], Convert.ToInt32(param[1])); // add to dictionary
            }


        }

        if (dict.ContainsKey(textBox1.Text) == false)
        {

        }
        else
        {
            MessageBox.Show("This name already exists!");
        }
    }

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
    {

        string Symbol = e.KeyChar.ToString();
        if (!Regex.Match(Symbol, @"[а-яА-Я]").Success && (Symbol != "\b"))
        {
            e.Handled = true;
        }


    }

1 Ответ

2 голосов
/ 31 мая 2019

Сначала я предлагаю методы извлечения , т.е.

using System.IO;
using System.Linq;

...

private static Dictionary<string, int> AllNames() {
  return File
    .ReadLines(@"C:\Users\HP\Desktop\картинки\results.txt")
    .Where(line => !string.IsNullOrWhiteSpace(line))
    .Select(item => item.Split(' ')) 
    .ToDictionary(items => items[0], 
                  items => int.Parse(items[1]));
}

private static bool NameExists(string name) {
  return AllNames().ContainsKey(name);
}

private static bool IsValidNameCharacter(char value) {
  // Russian letters are valid ones
  if (value >= 'А' && value <= 'Я' || 
      value >= 'а' && value <= 'я' || 
      value == 'ё' ||
      value == 'Ё')
    return true;

  // ...All the others are not 
  return false;
}

Тогда, чтобы предотвратить добавление русских букв в имена, давайте проверим textBox1.Text на TextChanged:

private void Button5_Click(object sender, EventArgs e) {
  if (NameExists(textBox1.Text)) {
    // Let us be nice: put keyboard focus on the problem field
    if (textBox1.CanFocus) {
      textBox1.Focus();
      // textBox1.SelectAll(); // if you want to select all the text
    }

    MessageBox.Show("This name already exists!");

    return; 
  }

  //given name passed validation control (name is all russian letters and unique)
  //TODO: put relevant code here (start the game?)
}

private void textBox1_TextChanged(object sender, EventArgs e) {
  textBox1.Text = string.Concat(textBox1.Text.Where(c => IsValidNameCharacter(c)));
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...