简体   繁体   English

如何解决在 C# 中获取列表框的选定字符串时出现此错误?

[英]How do I resolve this error in getting the selected string of a ListBox in C#?

I'd like to get a string of a Listbox.我想得到一个列表框的字符串。 This is my code:这是我的代码:

db.Employees.Select(x => x.LastName).OrderBy(x => x).ToList().ForEach(x => listBox1.Items.Add(x));
var selectedEmployee = listBox1.SelectedItem.ToString();
Debug.WriteLine(selectedEmployee);

The error I got is System.NullReferenceException .我得到的错误是System.NullReferenceException Not sure why though.不知道为什么。

So how do I fix this error?那么我该如何解决这个错误呢? By the way, everything is in the Window_Loaded method.顺便说一句,一切都在Window_Loaded方法中。

As @ElyasEsna said, you never set listBox1.SelectedItem, and that's why it throws NullReferenceException.正如@ElyasEsna 所说,您从未设置listBox1.SelectedItem,这就是它抛出NullReferenceException 的原因。

So I rewrote your code this way:所以我用这种方式重写了你的代码:

db.Employees.Select(x => x.LastName).OrderBy(x => x).ToList().ForEach(x => listBox1.Items.Add(x));
listBox1.SelectedItem = // list item that you will select, depending on the choice of your program
var selectedEmployee = listBox1.SelectedItem.ToString();
Debug.WriteLine(selectedEmployee);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM