0

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{
                }

             }
    
         }
A.Mac
  • 203
  • 3
  • 19
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Rahul Sharma Jan 12 '22 at 16:49
  • @RahulSharma. Not it does not. string cname = null; company = (this.FormView1.FindControl("companyname") as System.Web.UI.WebControls.TextBox).Text ?? "empty"; – A.Mac Jan 12 '22 at 17:13

1 Answers1

0

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?
}
JobesK
  • 347
  • 1
  • 2
  • 6
  • I updated the code snippet in my question. How do I get it to work inside of the FormView1.CurrentMode == FormViewMode.ReadOnly if statement? It works fine outside of it – A.Mac Jan 12 '22 at 19:56