|
-
March 18th, 2012, 10:42 AM
#7
Re: Need Help with Parser C#
 Originally Posted by dahrull
When I try to use the Try Catch method the form runs, however it doesn't work. No matter what I type into inputBx nothing will show in the outputBx.
I'm wanting this to work with the click of a button, but right now the important thing is making sure it actually all works first.
The exact same thing happens when I use TryGetValue.
Perhaps you could look at my code as a whole to see if I'm doing something wrong.
Code:
//Dictionary Load Button
private void button1_Click_1(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK) //Allows the user to choose the dictionary to load
{
Dictionary<string, string> d = new Dictionary<string, string>();
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] splitword = line.Split(',');
d.Add(splitword[0], splitword[1]);
string outputString = null;
if (d.TryGetValue(inputBx.Text, out outputString))
{
// We have found the string
outputBx.Text = outputString;
}
else
{
// Haven't found it - do something else
}
}
}
}
}
This returns no errors, runs the form, lets me load a text file for the streamreader but it still doesn't work with what I put into the text boxes
EDIT: Maybe I actually have to do this on a button_click event before it will work. Either way i'm still stuck. I'll admit I'm a starter at c# so I'm still learning "the ropes"
To (mis)quote the late, great Eric Morecambe, "you are using all the right code, but not necessarily in the right order" 
When the user clicks the button, your code is prompting the user for the dictionary file, reading it in (in the while loop) and (also in the while loop) checking in the dictionary. If you do want to read the file on each button click, it would be simpler just to check each line in turn against the text box. No need for a dictionary at all.
But, the better design would be this (IMHO ):
1) Read the file in when the dialog first opens, and set up the dictionary. This dictionary will need to be stored in the form so it can be accessed by the click handler.
2) Let the user type what they want in the text box
3) When the user clicks the button, check for this text in the dictionary, and set the output box appropriately.
You could also have another button which would prompt for a new file when clicked, and recreate the dictionary based on this file.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|