【问题标题】:how to store value in dictionary? [duplicate]如何在字典中存储值? [复制]
【发布时间】:2021-04-23 13:25:40
【问题描述】:

我使用以下get set 方法创建了一个Windows 窗体应用程序。 name, emailphone 是硬编码的,因此可以通过创建对象来存储值

    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;

但是对于工具来说,comboBox用于数据来自txt文件的地方

       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();
      }

如何将其数据存储在字典中? 我尝试使用相同的概念

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

但得到 System.NullReferenceException: '对象引用未设置为对象的实例。'错误

【问题讨论】:

  • 什么是Ratingr.facilities 在添加之前初始化?
  • 在哪里创建名称为parking facility 的组合框?您想在一个组合框中显示所有设施吗?
  • 一个组合框中没有一个设施我试图获取价值并存储在字典中。
  • 确实,facilities 永远不会被实例化,并且起始值是默认的 null 引用。所以你需要按照@noviceinDotNet 的指示创建一个对象
  • 是的,我明白了,非常感谢您的帮助

标签: c# .net visual-studio winforms combobox


【解决方案1】:

可枚举对象需要初始化。

r.facilities = new Dictionary <String,String>();
r.facilities.Add ("parking facility", parking.Text);

【讨论】:

  • OP 也可以使用public Dictionary&lt;String, String&gt; facilities { get; set; } = new Dictionary &lt;String,String&gt;(); 等默认值,并在相关时添加readonly 修饰符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 2017-01-19
  • 2018-08-14
  • 1970-01-01
  • 2023-03-03
  • 2018-08-23
相关资源
最近更新 更多