views:

433

answers:

2

Hello,


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

A: 

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.

public void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
     TextBox1.Text = ((TextBox)GridView1.Rows[e.RowIndex]
                              .FindControl("textBoxNotes")).Text;
}
dr
A: 

The manner you're referring to in the Page_Load occurs before the gridview's rows actually exist. Because it's occuring on the PostBack, the GridView (and firing events) must be recreated (re: its rows populated) from the ViewState. While the objects on the page have been initted and their values have been populated, the GridView has not been recreated yet and its events have not fired.

As dr mentioned, this should be done in the RowUpdating event.

Joel Etherton