简体   繁体   English

文件中的空引用

[英]Null Reference in file

I am getting and error on this line: 我在这一行得到了错误:

String selectedValue = this.employeeList.SelectedValue.ToString();

The error I am getting is 我得到的错误是

NullReferenceException was unhandled. NullReferenceException未处理。

What does this mean? 这是什么意思? Can someone help me understand why I am getting this error. 有人可以帮助我理解为什么我会收到此错误。 Down below is the whole code. 下面是整个代码。

String filePath = this.txtFilePath.Text;
if (!String.IsNullOrEmpty(filePath))
{
    MessageBox.Show("No file path specified");
}

if (this.employeeList.SelectedIndex != -1)
{
    String selectedValue = this.employeeList.SelectedValue.ToString();
    using (StreamWriter writer = new StreamWriter(filePath, true))
    {
        writer.WriteLine(selectedValue);
    }
}
else
{
    MessageBox.Show("No item selected");
}

That means you are trying to access something which is null (not initialized to any valid value). 这意味着您正在尝试访问null(未初始化为任何有效值)的内容。 So add a null check before accessing that. 所以在访问之前添加一个空检查。

I guess in this case, the employeeList.SelectedValue is probably null. 我想在这种情况下, employeeList.SelectedValue可能为null。

String selectedValue = string.Empty;
if(this.employeeList.SelectedValue!=null)
{
  selectedValue = this.employeeList.SelectedValue.ToString();
}
else
{
  MessageBox.Show("Please select any value");
}

If you run into any such errors , Always use Visual Studio Breakpoints and Step thru line by line to see what values are coming and where it is breaking. 如果遇到任何此类错误,请始终使用Visual Studio断点并逐行执行,以查看将要发生的值和断开的位置。 That is the best way to understand what is wrong with the code. 这是了解代码错误的最佳方法。

It means that this.employeeList.SelectedValue has a null value. 这意味着this.employeeList.SelectedValue具有空值。

A null object (SelectedValue) has no methods, so you can't call .ToString() on it. null对象(SelectedValue)没有方法,因此您无法在其上调用.ToString()。

Investigate why this.employeeList.SelectedValue would be null and you will find the source of your problem. 调查为什么this.employeeList.SelectedValue为null,您将找到问题的根源。

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

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