Search code examples
c#asp.nettelerikobject-referenceradtextbox

radtextbox avoid object throwing Object reference not set to an instance of an object


Which is a better code to avoid throwing Object reference not set to an instance of an object when using Telerik Radtextbox? Are both codes below the same? Can I set a default value to avoid nullreference from throwing?

protected void btnAddSAles_click(object sender, EventArgs e)        
{  
   string orderName = Ordername.Text;
}

or

protected void btnAddSAles_click(object sender, EventArgs e)        
{    
   TextBox b = item.FindControl("Ordername") as TextBox;            
   string box1 = b.text;            
}

Solution

  • I am assuming FindControl is returning null from the as cast you're trying to make. I assume (again) it isn't finding a control named Ordername, hence you are trying to access a Text property on a null object, which causes the NullReferenceException.

    What you should do is:

    1. Check why there is no control named Ordername, as im assuming there should be one
    2. If the control which invoked the Button.Click may not always be a TextBox object, add a nullity check:

      protected void btnAddSAles_click(object sender, EventArgs e)        
      {    
         TextBox b = item.FindControl("Ordername") as TextBox;      
         if (b != null)
         {      
            string box1 = b.text;
         }           
      }