Question

I am a "new" beginner in C# and on doing my Project i get one problem i can't solve with my knowledge. I try a lot but it dosent work for me so i hope i can get some help.

public void ReadValue()
{
  foreach(string cat in this.ini.iniGetCategories())
   {
     textbox1.Text = string.Join(Environment.NewLine , this.ini.iniGetCategories()) + Environment.NewLine + string.Join(Environment.NewLine, this.ini.iniReadValue(cat,"Key");
   }
}

this.ini.iniGetCategories() - reads all Sections from my INI -- works fine

this.ini.iniReadValue(string Section, string Key) - reads the Value from the Key from the Section

The main Problem is, that it gives me all Section - names but it only gives me the last Key + Value from my INI and ignores the other one

29.01.2014 - 10.00 My actually Code what gives me only "1 Section + 1 Value". The other are still missing...

StringBuilder strbuild1 = new StringBuilder();


            foreach (string cat in this.ini.IniGetCategories())
            {
                strbuild1.Append(cat + Environment.NewLine);

                foreach (string ccat in this.ini.IniGetCategories())
                {
                    strbuild1.Append(this.ini.IniReadValue(ccat, "Betreff"));
                }
            }

            textBox1.Text = strbuild1.ToString();
Was it helpful?

Solution

your foreach loop will assign textbox1.Text each time, so it's perfectly normal that only the last cat in this.ini.iniGetCategories() will be used to assign a retrieved value to the TextBox.

If I'm correct in assuming, that you'd like to have ALL category names in that TextBox, you would first construct a String (using either the += operator or, preferably, using the StringBuilder class and only AFTER the scope of the foreach loop ends would you then assign that string to the Text property of your TextBox.

An easy and readable way to achieve this, is to use double nested loops.

the general idea is: for each section in the collection of sections, then for each key in the collection of keys for that specific section

OTHER TIPS

As Wim mentioned using the += operator is useful on your case.

public void ReadValue()
{
  foreach(string cat in this.ini.iniGetCategories())
   {
     textbox1.Text += string.Join(Environment.NewLine , this.ini.iniGetCategories());
     textbox1.Text += string.Join(Environment.NewLine, this.ini.iniReadValue(cat,"Key");
   }
}

Sorry for the shameless plug but I would like to introduce IniParser, a library I've created. MIT license (can be used even in proprietary code) Written in c# w/out external bindings, so it contains no dependencies in any OS, which makes it Mono compatible.

You can check out the source in GitHub, and it is also available as a NuGet package

It's heavily configurable, and really simple to use.

Hope it can be of help of anyone revisiting this answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top