简体   繁体   中英

Change value of control in GridView edit template

I've got a GridView and I need to be able to programmatically change the value of a TextBox in the edit template. When I attempt to access it during onRowDataBound I get this:

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

I am thinking that inside the onRowDataBound method, the edit template controls are not accessible. When I attempt to edit the TextBox's value in the onRowEditing method, however, there is no .Row option for the GridViewEditEventArgs object, so it appears that you can't access controls in the edit template in the onRowEditing method either.

Any ideas how to programmatically change the value of a TextBox in a GridView's edit template?

ASP.NET WebForms, .NET 4.0, C#

====

Edit #1: This is what I currently have. The txtMiles object ends up being null 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();
            }

Just make sure the row is in edit mode before you try and 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";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM