在GridView编辑模板中更改控件的值

时间:2014-02-05 14:44:15

标签: c# asp.net .net gridview webforms

我有一个GridView,我需要能够以编程方式更改编辑模板中TextBox的值。当我在onRowDataBound期间尝试访问它时,我得到了这个:

异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。

我想在onRowDataBound方法中,无法访问编辑模板控件。但是,当我尝试在onRowEditing方法中编辑TextBox的值时,GridViewEditEventArgs对象没有.Row选项,因此看起来您无法在onRowEditing方法中访问编辑模板中的控件。

如何以编程方式更改GridView编辑模板中TextBox的值?

ASP.NET WebForms,.NET 4.0,C#

====

编辑#1:这就是我现在拥有的。在RowEditing中,txtMiles对象最终为null。

<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();
            }

1 个答案:

答案 0 :(得分:4)

在尝试获取控件之前,请确保该行处于编辑模式:

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";
    }
}