Skip to main content
 首页 » 编程设计

c#之在 C# 中设置列表框的数据源时如何避免 NullReferenceException

2024年02月06日16telwanggs

我正在尝试将以下代码添加到我的表单中:

List<string> list = new List<string>(); 
list.Add("1"); 
list.Add("2"); 
list.Add("3"); 
list.Sort(); 
listBox5.DataSource = list; 

尝试运行代码时,出现错误:

"NullReferenceException was unhandled: Object reference not set to an instance of an object."

我该如何解决这个问题?

请您参考如下方法:

您可能在调用 InitializeComponent() 之前将此代码放在窗体构造函数中。 引用表单对象的代码应始终放在 InitializeComponent()

之后