ASP.NET Formview Textbox value- Object reference not set to an instance of an object

199 Views Asked by At

I would like to know whether or not this control is null once the page loads before I perform another operation. At the moment it just throws the object reference error.

       protected void FormView1_DataBound(object sender, EventArgs e)
        {
    
            if (FormView1.CurrentMode == FormViewMode.ReadOnly)
            {
    
                string cname =  
                (this.FormView1.FindControl("companyname") as 
                System.Web.UI.WebControls.TextBox).Text;

                if (cname == null)
                { 

                }
                else{
                }

             }
    
         }
1

There are 1 best solutions below

1
JobesK On

check for textbox first (make sure thats the ID youre looking up), something like,

TextBox compName = (Textbox)this.FormView1.FindControl("companyname");
string cName = "";
if(compName != null)
{
      cName = compName.Text;
}
else
{
  // textbox not found! do something?
}