尽管所引用的内容不为null,如何修复“ nullreferenceexception”?

时间:2019-06-13 00:51:27

标签: vb.net

使用下面的代码引用单选按钮,试图找到选中的按钮,并不断抛出NullReferenceException。我尝试同时引用它的.name和.tag属性,并且它们都在前几次尝试中都起作用,但是尽管它们所引用的内容没有任何变化,但他们开始抛出NullReferenceExceptions。

在Visual Studio上,尝试将.name更改为。

    Dim strRBName As String = grpGrams.Controls.OfType(Of RadioButton).FirstOrDefault(Function(r) r.Checked = True).Name.ToString

我希望它输出用于快速数学运算的标记,但是当抛出异常时,我切换到它,抛出.name进行更多恼人的解决方法,直到该异常开始引发相同的异常。

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=Shopping Cart Project
  StackTrace:
   at Shopping_Cart_Project.Form1.ChangeDisplayedPrice(Object sender, EventArgs e) in C:\Users\Iyan D Barone\source\repos\Shopping Cart Solution\Shopping Cart Project\Form1.vb:line 62
   at System.Windows.Forms.RadioButton.OnCheckedChanged(EventArgs e)
   at System.Windows.Forms.RadioButton.set_Checked(Boolean value)
   at Shopping_Cart_Project.Form1.InitializeComponent() in C:\Users\Iyan D Barone\source\repos\Shopping Cart Solution\Shopping Cart Project\Form1.Designer.vb:line 180
   at Shopping_Cart_Project.Form1..ctor() in C:\Users\Iyan D Barone\source\repos\Shopping Cart Solution\Shopping Cart Project\Form1.vb:line 6

1 个答案:

答案 0 :(得分:0)

要调试,请尝试将其分为更多步骤:

419 | Page Expired.

在第一行之后检查rb的值。如果为null(如果没有控件是单选按钮或未选中任何控件,则为null),这就是问题所在。上面的代码可以工作,尽管它更紧凑一些:

<script type="text/javascript" src="/SiteAssets/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="/SiteAssets/jquery-3.4.1.js"></script>
<script type="text/javascript">
        function PreSaveAction() {
drop1 = $("select[title='Supervisor Completed']").val();
date1 = $("input[title='Supervisor Date Completed']").val();
drop2 = $("select[title='IMO Completed']").val();
date2 = $("input[title='IMO Date Completed']").val();
drop3 = $("select[title='IAM Completed']").val();
date3 = $("input[title='IAM Date Completed']").val();
    if (drop1 !=="Select One..." && date1===""){
        alert("The Supervisor Date Completed is a required element. Please Fill this date out.");
        return false;
    }    
        return true;
}
    if (drop2 !=="Select One..." && date2===""){
        alert("The IMO Date Completed is a required element. Please Fill this date out.");
        return false;
    }    
        return true;
}
    if (drop3 !=="Select One..." && date3===""){
        alert("The IAM Date Completed is a required element. Please Fill this date out.");
        return false;
    }    
        return true;
}
        }
</script>

请注意? .Name之前要处理Null值,并且Name已经是一个字符串,因此您不需要ToString()