Search code examples
c#winformsdropdownrichtextboxfilereader

Read text from selected file in dropdown to richtextbox


I'm trying to make a quick tool to edit a monitor configuration, namely to acknowledge a monitor being down or not. The files are .yml files but the contents are clear text Specifically the line reads: docMeta.DownAcknowledge: False

I'd like a tool to be able to change this line to either True or False, depending on the situation.

configDropDown.Items.Clear();
string[] files = Directory.GetFiles(@"d:\monitors.d\");
foreach (string file in files)
configDropDown.Items.Add(Path.GetFileNameWithoutExtension(file));

This populates my dropdown box as it should, however, I can't figure out how to get the contents of the selected file into my richtextbox.

In the configDropDown_SelectedIndexChanged

I've got the following:

// get the value (file path)
string fileName = (string)configDropDown.SelectedItem;
string filePath = Path.Combine(@"d:\monitors.d\", fileName + ".yml");

if (File.Exists(filePath))
    configReader.AppendText(File.ReadAllText(filePath));
else
    configReader.Clear();

But nothing happens when I select something from my dropdown. Originally I just wanted to pull the docMeta.DownAcknowledge: line, but couldn't get this to work, so tried just reading the entire file.

If you could show me how I could edit the docMeta.DownAcknowledge: line to either True/False and save it as well, that will be my next hurdle.

Thank you very much in advance.


Solution

  • Your code seems to be work OK. I suspect the problem is that your SelectedIndexChanged event isn't hooked up.

    If you open your [FormName].Designer.cs file and have a look at the Generated Code. Can you see the following line for your configDropDown control:

    this.configDropDown.SelectedIndexChanged += new System.EventHandler(this.configDropDown_SelectedIndexChanged);
    

    If it isn't there, you can add it using the code above.