So, I am about to conclude a (gulp) three-day battle with a FormView and trying to find controls in it using FindControl. In general, I have a hard time using FindControl. It seems like everytime I have to use it, I run into trouble.
There were a number of really dumb mistakes that I made that I had to work through. Things like not binding my data source to the FormView. That made it hard for FindControl to find anything. But once I got through the dumb mistakes, I couldn't figure out why this code wouldn't work.
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
// if this SQL syntax doesn't look familiar, it's because it's MySQL
string mySQL = "SELECT `recipe_name` FROM `recipes` WHERE `recipe_idno` = 10";
// DALquery is a class I wrote to handle data transactions against my database and it worked just fine.
DALquery myQuery = new DALquery(mySQL);
FormView1.DataSource = myQuery.getDataSet();
FormView1.DataBind();
TextBox tbRecName = (TextBox)FormView1.FindControl("TextBoxRecipeName");
Response.Write(tbRecName.Text); // this line causes an error!
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title>Untitled Page</title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:FormView ID="FormView1" runat="server">
<EditItemTemplate>
<fieldset><legend>Some Legend</legend>
<label>Some Label:</label>
<asp:TextBox ID="TextBoxRecipeName" runat="server" Text='<%# Bind("recipe_name") %>'></asp:TextBox><br />
</fieldset>
</EditItemTemplate>
</asp:FormView>
</div>
</form>
</body>
</html>
When I ran it, I get the error message "Object reference not set to an instance of an object." at the Response.Write() line noted in the code above. You know, you read on forums where programmers fight with something for several hours or maybe a day, but when I start getting into multiple days, you may find me under my desk in the fetal position whimpering something like "I'm never gonna be a real programmer."
As it turns out, the solution was incredibly simple. The issue lies in the current mode of the FormView when FindControl is executed. By default, the FormView is in "read-only" mode. More on that here. Since the text box I was trying to find was inside an "EditItemTemplate", FindControl couldn't find it.
So, to resolve the problem, I had to explicitly set the mode for the FormView to "edit" like this:
<asp:FormView ID="FormView1" runat="server" DefaultMode="Edit">
And the code works now. Well, one more baby step in my growth, I guess.