Question


I'm quite new to c# programming and I got myself a nice little problem now, and I would be very greatfull for some help.
I know that my example below isn't going to work, but it is just to give you an idea of what i'm trying to do.
The thing is that I want different textBoxes to be updated with the content of the file depending on the file name... So how do you assign textBox.text or textBox to something?

public void OnChanged(object source, FileSystemEventArgs e)
{
   string newPath = Path.Combine(activeDir, "Files");
   string fileName = e.Name;

   if (fileName.StartsWith("O1"))
     TextBox txtBox = textBoxNC1;
   if (fileName.StartsWith("O2"))
     TextBox txtBox = textBoxNC2;
   if (fileName.StartsWith("O3"))
     TextBox txtBox = textBoxNC3;
   if (fileName.StartsWith("O7"))
     TextBox txtBox = textBoxNC4;
   if (fileName.StartsWith("O0"))
     TextBox txtBox = textBoxNC5;

   StreamReader rdr = new StreamReader(file);
   txtBox = rdr.ReadToEnd();
   rdr.Close();
}

Sincerely
Hjalmarsson

Was it helpful?

Solution

You're on the right lines.

You just make sure you declare the TextBox outside the if test assign the Text property:

TextBox txtBox;
if (fileName.StartsWith("O1")
{
    txtBox = textBoxNC1;
}
....

if (txtBox != null)
{
    txtBox.Text = rdr.ReadToEnd();
}

OTHER TIPS

A little bit of different approach to elimate the ifs using generic Dictionary:

Dictionary<string, TextBox> lookup = new Dictionary<string, TextBox>();

lookup["O1"] = textBoxNC1;
lookup["O2"] = textBoxNC2;
lookup["O3"] = textBoxNC3;
lookup["O7"] = textBoxNC4;
lookup["O0"] = textBoxNC5;

var prefix = fileName.SubString(0, 2);

if (lookup.ContainsKey(prefix))
{
  using (var reader = new StreamReader(file))
  {
    lookup[prefix].Text = reader.ReadToEnd();
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top