On my page I’ve defined controls TextBox1, Label1 and GridView1. Inside GridView1 I’ve defined the following template:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" Text="Edit" CommandName="Edit" ID="cmdEdit" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox Text='<%# Bind("Notes") %>' runat="server" id="textBoxNotes" />
<br /><br />
<asp:LinkButton runat="server" Text="Update"
CommandName="Update" ID="cmdUpdate" />
<asp:LinkButton runat="server" Text="Cancel"
CommandName="Cancel" ID="cmdCancel" />
</EditItemTemplate>
</asp:TemplateField>
If user enters a text into textBoxNotes and clicks cmdUpdate button, then on postback this text will already be available when Page_Load() is called.
Thus, if user, before clicking the update button cmdUpdate, also entered into TextBox1 a string “something”, then the following code will extract the text user entered into textBoxNotes
protected void Page_Load(object sender, EventArgs e)
{
if(TextBox1.Text=="text from Notes")
Label1.Text =((TextBox)gridEmployees.Rows[0].Cells[0].FindControl("textBoxNotes")).Text;
}
A) The following code should also extract the text user entered into textBoxNotes, but the moment I click cmdEdit button, I get “Object reference not set to an instance of an object.” exception
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
Label1.Text =((TextBox)gridEmployees.Rows[0].Cells[0].FindControl("textBoxNotes")).Text;
}
Why do I get this exception? It appears as if textBoxNotes doesn’t exist. But why wouldn’t it exist?
thanx
Best Answer
When the Update event occurs, the row is no longer in edit mode. Therefore textBoxNotes does not exist on the page. Use the RowUpdating event handler of the gridview to access the edit template controls.