c# с визуальной студией windows форма | Как найти текстовое поле ввода в файл и вернуть поиск - PullRequest
0 голосов
/ 08 апреля 2020

Я новичок в C#, и я пишу проект, в котором я создал метод для чтения текстового файла. У меня есть текстовое поле с кнопкой поиска. Программа должна прочитать входные данные в текстовом поле, выполнить поиск в методе файла и представить соответствующий результат в списке. У меня уже есть такая кодировка, но она ничего не возвращает. Кто-нибудь может мне помочь?

    private void searchButton_Click(object sender, EventArgs e)
    {
        String[] findValues = this.nameTextBox.Text.Split(new String[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        string newline = string.Empty;
        gameListBox.Items.Clear();
        ReadIntoArray();
        string[][] games = new string[16][];

        var index = BinSrchByName(nameTextBox.Text);

        if (index != -1)
        {
            gameListBox.Items.Add(names[index] + " ==> $" + sales[index]);
        }
        else
        {
            MessageBox.Show("Data not found");

        }

Ответы [ 2 ]

1 голос
/ 08 апреля 2020

Пожалуйста, попробуйте следующее (я написал несколько комментариев, чтобы помочь вам понять мой метод):

    // Declare a list to hold the file lines
    List<string> FileLines = new List<string>();

    private void button_BrowseFile_Click(object sender, EventArgs e)
    {
        // Open a file dialog
        using (OpenFileDialog openDialog = new OpenFileDialog())
        {
            // Set the file dialog to show only *.txt file or all files
            openDialog.Filter = "Text files (*.txt)|*.txt|All Files (*.*)|*.*";

            // Allow only single file selection
            openDialog.Multiselect = false;

            // Make sure the user didn't clicked the 'Cancel' button
            if (openDialog.ShowDialog(this) == DialogResult.OK)
            {
                // Update the current file label with the filename only (not the full path)
                label_CurrentFile.Text = $"Current file: {Path.GetFileName(openDialog.FileName)}";

                // Add each line of the txt file into the list
                foreach (string line in File.ReadAllLines(openDialog.FileName, Encoding.UTF8))
                    FileLines.Add(line);
            }
        }
    }

    private void button_DoSearch_Click(object sender, EventArgs e)
    {
        // Clear the list
        list_SearchResults.Items.Clear();

        // Count the number of line so you will be able to present it on the results list later on
        int iLineNumber = 1;

        // For each item in the 'FileLines' list
        foreach (var item in FileLines)
        {
            // Check whether the current line contains the term the user typed in the searchbox
            // I'm using 'ToLower()' to ignore case
            if (item.ToLower().Contains(text_SearchTerm.Text.ToLower()))
            {
                // Create new ListViewItem to be added later on to the results list
                // Add the first column the complete line that contains the term in the searchbox
                ListViewItem lvi = new ListViewItem(item);

                // Add the line number to the second column
                lvi.SubItems.Add(iLineNumber.ToString());

                // Add the ListviewItem to the results list
                list_SearchResults.Items.Add(lvi);
            }

            // Increment the line number variable
            iLineNumber++;
        }
    }

Скриншоты:

Screenshot1

Screenshot2

Надеюсь, это поможет!

0 голосов
/ 08 апреля 2020

Эта функция получает путь к файлу и искомое слово, проходит через весь текстовый файл и возвращает строку, в которой было найдено запрошенное слово.

private string SearchText(string archivetxt, string word) {
    StreamReader sr = new StreamReader(archivetxt);
    while (!sr.EndOfStream) {
        string s = sr.ReadLine();
        if (s.IndexOf(word) > -1)
            return s;                
    }
    sr.Close();
    return word + " not found";
}
...