Hello everyone,

I'm having trouble making a search box for my program.

This is a not a school project or anything, just a personal project I've been working on. Therefore, any possible solutions are welcomed.

This is basically a program is a dictionary program of sorts. The user enters in a word and a definition. The word is then stored in a collection (WordCollection), and this collection is the datasource for a listbox control which the user scrolls through to find words/definitions.

The problem I have is not with the program, but the import/export and search functionality within the program.

Right now, I am using .csv format to import/export the file. The exported lines would look something like this:

the garbage people throw out, garbage is waste

The problem is when I have two definitions like this:

i'm a pig, you're not a pig // fails search
i am a pig, you're not a pig // fails search
immediate, right now // works, so I assume there is a problem with space/apostrophe in my search mechanism right now

Here's the code I'm using at the moment.

// sort in alphabetical order
words.Sort(delegate(Word x, Word y) { return String.Compare(x.WordInput, y.WordInput); });

foreach (Word word in words)
{
    if (word.WordInput == txtSearch.Text)
    {
        int index = words.IndexOf(word);

        lstWordList.SetSelected(index, true);

        break; // select the first match
    }
}

Any help or solution would be appreciated.

I also wanted to point out that .NET has a Dictionary<> class that may do what you want. Other than that i'll wait next to danny on seeing more code.

Could you please be a bit more elaborate on the code?
What is Word etc.

Well I want to paste the code, but its pretty big. =(

Basically, I have a program that loads up a listbox full of Words.

Words is a class that holds a word and a definition;
ie
Word Object = private string word, definition; + getters/setters.

WordCollection is an a collection that holds a bunch of words.

This collection is the datasource for my listbox.

Is there any specific part of the code you want to see? I can just paste some parts I think that are important.

The import and export code:

private void exportDatabase()
        {
            string path = @"C:\Program Files\Kotoba\data.csv";

            if (File.Exists(path))
            {
                try
                {
                    StreamWriter streamWriter = new StreamWriter(path);

                    foreach (Word wordItem in words)
                    {
                        streamWriter.WriteLine(wordItem.SaveData());
                    }

                    streamWriter.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + "\n");
                }
            }
        }

        private void importDatabase()
        {
            string path = @"C:\Program Files\Kotoba\data.csv";

            if (File.Exists(path))
            {
                try
                {
                    StreamReader streamReader = new StreamReader(path);
                    char[] delims = { ';' }; // for setting delimiters

                    while (streamReader.Peek() > 0) // if item exists
                    {
                        // read in values line by line
                        string line = streamReader.ReadLine();

                        // seperate values into array
                        string[] splitValues = line.Split(delims);

                        // add word to the listbox
                        Word word = new Word(splitValues);
                        words.Add(word);
                    }

                    // sort in alphabetical order
                    words.Sort(delegate(Word x, Word y) { return String.Compare(x.WordInput, y.WordInput); });

                    streamReader.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message + "\n");
                }
            }
        }

You can zip the project and upload it to the thread. Hit the "Go Advanced" button next to "Post Quick Reply" and it will let you manage attachments.

[edit]
Are you also looking for suggestions on other ways to store the data (such as XML) instead of CSV? It may make life a little easier
[/edit]

Edited 7 Years Ago by sknake: n/a

Hi sknake,

Yes, I was looking for some insight if there was maybe a better option than a csv file. I'm still currently a student, so my programming skills are still being worked on. However, I have worked with SQL before and was thinking of doing something along those lines in the future. For now, I just wanted to get something quick and dirty going. I wanted it to be functional before I revised it to an SQL database. I was debating scrapping csv and going xml today. Anyways, you guys can take a look at my code and see whats going on.

Things that are bugged out is basically the search function when I use words that start with the letter I. Single word strings work, but multi-word strings are messed. Multi-word meaning "I am new" or "I'm a person". Anyways, take a look, the installer is also included.

I don't understand what part of your search mechanism that is broke exactly. Would you give us the definitions you have, the searched criteria used, and whether or not they should match? A few examples would be helpful

Also for saving your data in XML:

Definition.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace daniweb.dictionary
{
  public class Definition
  {
    public string Word { get; set; }
    public string WordDefinition { get; set; }
    public Definition()
    {
    }
    public Definition(string Word, string Definition)
      : this()
    {
      this.Word = Word;
      this.WordDefinition = Definition;
    }

    /// <summary>
    /// Saves the dictionary collection to a file
    /// </summary>
    /// <param name="dictionary">Populated dictionary</param>
    /// <param name="FileName">Filename to save to</param>
    public static void SaveToFile(SortedDictionary<string, string> dictionary, string FileName)
    {
      List<Definition> lst = new List<Definition>();
      foreach (KeyValuePair<string, string> kvp in dictionary)
      {
        lst.Add(new Definition(kvp.Key, kvp.Value));
      }
      XmlSerializer ser = new XmlSerializer(typeof(List<Definition>));
      using (FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write))
      {
        ser.Serialize(fs, lst);
      }
    }

    /// <summary>
    /// Loads a dictionary from a saved state
    /// </summary>
    /// <param name="FileName">Filename containing the words</param>
    /// <returns></returns>
    public static SortedDictionary<string, string> FromFile(string FileName)
    {
      SortedDictionary<string, string> result = GetNewDictionary();

      List<Definition> lst;
      XmlSerializer ser = new XmlSerializer(typeof(List<Definition>));
      using (FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read))
      {
        lst = (List<Definition>)ser.Deserialize(fs);
      }
      foreach (Definition def in lst)
      {
        if (!result.ContainsKey(def.Word))
          result.Add(def.Word, def.WordDefinition);
      }
      return result;
    }

    /// <summary>
    /// Creates a new case-insensitive dictionary
    /// </summary>
    /// <returns></returns>
    public static SortedDictionary<string, string> GetNewDictionary()
    {
      return new SortedDictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
    }
  }
}

Calling it:

private void btn1_Click(object sender, EventArgs e)
    {
      //Definition.SaveToFile(words, GetDefaultFileName());
      var dict = Definition.GetNewDictionary();
      dict.Add("Apple", "A fruit");
      dict.Add("Orange", "A fruit");
      dict.Add("Termites", "A vegetable");
      Definition.SaveToFile(dict, "C:\file.txt");

      //load it back
      var newDict = Definition.FromFile(@"C:\file.txt");
    }

The problem with the search mechanism is that when I search a single word in the "I" category, things get messed up.

For example, when you run the program, enter in some sample words like this:

word = immediate, definition = at this moment // this will search properly because it is a single word lookup (immediate)

however, when you use sentences start with "i xxx xxx" (i space xxx) or "i'm xxx" (i apostrophe xxx), the mechanism gives me random results.

put in these three samples and try to search for them and you will understand what i mean.

Word / Definition
============
immediate / right now
i'm tom / this is tom
i am going crazy / this doesn't sound normal

enter these 3 samples, and try to searching them up. It only happens with the "I" words/definitions for some weird reason, it works for every other letter in the alphabet. really strange.

I have no idea how to reproduce that problem. I can't get your program to work the way you're explaining :(

I have no idea how to reproduce that problem. I can't get your program to work the way you're explaining :(

Did you try installing the program? With this reply, I've included the installer. Just run the installer, next, next, next. Then put this data.csv file (attached with this post), in C:\Program Files\Kotoba (not inside C:\ProgramFiles\Kotoba\KotobaSetup).

Now with the file there, when the program opens, it will auto load the data into the listbox, and when u close the program, it will auto save the data into the same csv file and update it accordingly.

Try searching for one the words without the definition. ie) itai = hurt | In the search box, type in itai and it should highlight (select) itai = hurt in the listbox. Try it with the other strings and it acts funny or will select the wrong item.

Hope this helps clear it up a little.

This article has been dead for over six months. Start a new discussion instead.