【发布时间】:2021-04-23 13:25:40
【问题描述】:
我使用以下get set 方法创建了一个Windows 窗体应用程序。 name, email 和 phone 是硬编码的,因此可以通过创建对象来存储值
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: '对象引用未设置为对象的实例。'错误
【问题讨论】:
-
什么是
Rating和r.facilities在添加之前初始化? -
在哪里创建名称为
parking facility的组合框?您想在一个组合框中显示所有设施吗? -
一个组合框中没有一个设施我试图获取价值并存储在字典中。
-
确实,
facilities永远不会被实例化,并且起始值是默认的null引用。所以你需要按照@noviceinDotNet 的指示创建一个对象 -
是的,我明白了,非常感谢您的帮助
标签: c# .net visual-studio winforms combobox