-3

I have created a windows form application with the following get set method. The name, email and phone is hardcoded and thus the value can be stored by creating an object

    public string Name { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }

    public Dictionary<String, String> facilities { get; set; }


    Rating r = new Rating(); //object creating
        r.Name = txtName.Text; //get value from textbox and assing to property
        r.Email = txtEmail.Text;
        r.Phone = txtPhone.Text;

However for the facilities, comboBox is used where the data comes from txt file

       int locationX = 143;
        int locationY = 200;
        string line;
        System.IO.StreamReader file =
            new System.IO.StreamReader(@"facilities.txt");
        while ((line = file.ReadLine()) != null)
        {
            // Remove the extra ','
            string comboName = line.Substring(0, line.Length - 1);

            ComboBox comboBox = new ComboBox();
            comboBox.Name = comboName;
            comboBox.Items.AddRange(new object[] { 1, 2, 3, 4 });
            comboBox.Location = new Point(locationX, locationY);
            
            this.tabPage1.Controls.Add(comboBox);

            Label label = new Label();
            label.Text = comboName;
            label.Location = new Point(0, locationY);
            
            this.tabPage1.Controls.Add(label);


            locationY += 50;
        }

        file.Close();
      }

How can I store its data in the dictionary? I tried using the same concept

             ComboBox parking= (ComboBox)this.Controls.Find("parking facility", true)[0];
          //MessageBox.Show(parking.Text);
         r.facilities.Add("parking facility", parking.Text);

but got System.NullReferenceException: 'Object reference not set to an instance of an object.' error

Benzara Tahar
  • 2,058
  • 1
  • 17
  • 21
bone
  • 7
  • 4
  • What is `Rating` and is `r.facilities` initialized before adding something? – nilsK Jan 19 '21 at 09:03
  • Where do you create a combobox with name `parking facility`? Do you want to display all the facilities in one combobox? – Chetan Jan 19 '21 at 09:03
  • no one facility in one comboBox i was trying to get the value and store in dictionar. – bone Jan 19 '21 at 09:07
  • Indeed, `facilities` is never instantiated and the starting value is the default `null` reference. So you need to create an object as indicated by @noviceinDotNet –  Jan 19 '21 at 09:07
  • yes i got it thank you so much for helping – bone Jan 19 '21 at 09:08

1 Answers1

4

initialization necessary for enumerable objects.

r.facilities = new Dictionary <String,String>();
r.facilities.Add ("parking facility", parking.Text);
novice in DotNet
  • 771
  • 1
  • 9
  • 21
  • 1
    Also OP can use default value like `public Dictionary facilities { get; set; } = new Dictionary ();` and add the `readonly` modifier if relevant. –  Jan 19 '21 at 09:11