Why Null Reference Error Occurred?
Reference error only occurs when reference variable is getting null value. This error can also occur when object is not initialized or it is initialized but its value change nothing. Exception handling is very complex part. Dot net developers can handle/debug error using following ways:-
- Try-catch
- Breakpoints
- Quickwatch
- Callstack
Example: Suppose you went on date with your girlfriend and you purposed a ring as a gift to her in a enclosed box. But when she opened ring box , then she found nothing in ring box.That means Null reference error occurred and you are responsible for this.It does not mean that you have not brought a ring for her. It may happen that it is lost somewhere on road or somewhere else.
Null Exception Error Handling using OPCODE: Microsoft provide the OPCODE to handle this error. So you can simply throw this error.
Variable: variable are of two type one is value type and another is reference type.Value types are directly stores values but reference type variable needs to initialize.
- Value Type: int, float, decimal and double type.
- Reference Type: Class, delegates and string are reference type.
How to Avoid null Reference:
- Initialize reference variable
- Check value is null or not in incoming request
Fix radio Button Null Exception
The best way to check in visual studio is testing with debugger. so you need to check that is controls are created or not you need to check null value. You are doing it in a wrong way. The right way to find the control is below:
- First find the control RadioButton : r= Panel1.FindControl(“2”) as RadioButton;
- Then you need to check the data is null or not : if(r != null) //check for null reference
- Then enable Checked properties : r.Checked = true;
- Now you are able to find the control.
Program to check null reference in C#:
using System; class Program { static void Main() { // Create an array and use it in a method. int[] array = new int[2]; array[0] = 1; array[1] = 2; Test(array); // Use null reference in a method. array = null; Test(array); // <ā- Won't crash } static void Test(int[] array) { if (array == null) { // You can throw an exception here, or deal with the argument. return; } int rank = array.Rank; Console.WriteLine(rank); } }