WhereAreYouSyntax
WhereAreYouSyntax

Reputation: 163

Making a web form translator that uses a .csv file

I'm writing a web form that can convert abbreviations into their actual meaning. I'm using a .csv file with two columns separated by a ';' (that can change if needs be). The first column is going to be the user input (so the abbreviation) and the second column will be the output (the meaning). I'm fairly new to C# so I'm struggling a little but I think I'm on the right path with this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        private Dictionary<string, string> _dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); // let's ignore case when comparing.

        protected void Page_Load(object sender, EventArgs e)
        {
            using (var reader = new StreamReader(File.OpenRead(@"C:/dictionary.csv")))
            {
                while (!reader.EndOfStream)
                {
                    string[] tokens = reader.ReadLine().Split(';');
                    _dictionary[tokens[0]] = tokens[1];
                }
            }
        }

            protected void Button1_Click(object sender, EventArgs e)
                {


         string output;
                if(_dictionary.TryGetValue(TextBox1, out TextBox2))
                return TextBox2;

                throw new Exception("Input not recognised");
            }    
        }

    }
}

any help is greatly appreciated. The webform consists of the input (textbox1) the button and the output (textbox2)

EDIT for clarity

This wont run...

Upvotes: 0

Views: 104

Answers (1)

Bernhard Hofmann
Bernhard Hofmann

Reputation: 10391

I don't think this is good form, but for the simple use you have it should work:

protected void Button1_Click(object sender, EventArgs e)
{
    string output;
    if (_dictionary.TryGetValue(TextBox1.Text, out output))
    {
        TextBox2.Text = output;
    }
    else
    {
        TextBox2.Text = "Input not recognised";
    }
}

Upvotes: 2

Related Questions