Change control value in GridView edit template

I have a GridView, and I need to be able to programmatically change the value of the TextBox in the editing template. When I try to access it during onRowDataBound, I get the following:

Exception Details: System.NullReferenceException: The object reference was not set to the object instance.

I think that inside the onRowDataBound method, the edit controls are not available. However, when I try to change the TextBox value in the onRowEditing method, there is no .Row for the GridViewEditEventArgs object, so it seems that you also cannot access the controls in the editing template in the onRowEditing method.

Any ideas on how to programmatically change the value of a TextBox in a GridView editing template?

ASP.NET WebForms, .NET 4.0, C #

====

Edit # 1: This is what I have. The txtMiles object ends with a null value in RowEditing.

<asp:TemplateField HeaderText="Miles Frequency">
                    <ItemTemplate>
                        <asp:Label ID="lblFreqMiles" runat="server" Text='<%# Eval("FrequencyMiles") %>'></asp:Label>
                    </ItemTemplate>                    
                    <EditItemTemplate >
                        <asp:TextBox ID="txtFreqMiles" runat="server" Text='<%# Eval("FrequencyMiles")%>'  Width="50px"></asp:TextBox>
                        <asp:RequiredFieldValidator runat="server" ID="req1" ControlToValidate="txtFreqMiles" ErrorMessage="*" />
                        <asp:CompareValidator ID="CompareValidator1" runat="server" Operator="DataTypeCheck" Type="Integer" ControlToValidate="txtFreqMiles" ErrorMessage="Value must be a whole number." />
                    </EditItemTemplate>
                </asp:TemplateField>


    protected void gvMaint_RowEditing(object sender, GridViewEditEventArgs e)
            {
                //format Miles Frequency column
                GridViewRow row = grvMaint.Rows[e.NewEditIndex];
                TextBox txtMiles = (TextBox)row.FindControl("txtFreqMiles");
                if (txtMiles.Text == "999999")
                {
                    //do stuff
                }

                grvMaint.EditIndex = e.NewEditIndex;
                populateMaintGrid();
            }
+3
source share
1 answer

Just make sure the line is in edit mode before trying to get the control:

protected void gvMaint_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowState == DataControlRowState.Edit)
    {
        TextBox txtFreqMiles = (TextBox)e.Row.FindControl("txtFreqMiles");

        // At this point, you can change the value as normal
        txtFreqMiles.Text = "some new text";
    }
}
+4
source

All Articles