【问题标题】:Change value of control in GridView edit template在 GridView 编辑模板中更改控件的值
【发布时间】:2014-03-02 01:38:15
【问题描述】:

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

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

我认为在 onRowDataBound 方法中,编辑模板控件不可访问。但是,当我尝试在 onRowEditing 方法中编辑 TextBox 的值时,GridViewEditEventArgs 对象没有 .Row 选项,因此您似乎也无法在 onRowEditing 方法中访问编辑模板中的控件。

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

ASP.NET WebForms、.NET 4.0、C#

====

编辑#1:这是我目前拥有的。 txtMiles 对象在 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();
            }

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,但这给出了空引用异常:对象引用未设置为对象的实例。我确保做了所有显而易见的事情,比如将“yourTextBoxID”更改为控件的实际 ID。当我尝试访问 TextBox 对象的 .Text 值时,它给出了异常。 TextBox 对象为空。
    • @flying227 我是个白痴,我想。更新了我的答案。我在想(根据您的评论)您需要对该行进行数据绑定才能使控件在那里,因此您必须使用 RowDataBound 事件。但您需要确保 Row 处于编辑模式。
    猜你喜欢
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多