asp 更改 OnRowDataBound 事件中的文本后,Gridview 列变得不可编辑

asp Gridview column becomes not editable after changing the text in OnRowDataBound event

我使用 GridView 来显示和修改数据。但是我没有直接使用数据库中的数据,而是必须转换它们(考虑在不同的日期格式之间切换),所以在 RowDataBound 事件中我更新了一列的文本字段。但是,当捕获到 OnRowEditing 事件时,该数据列之后变得不可编辑。

代码:

    public void OnRowEditing(Object sender, GridViewEditEventArgs e)
    {
        gv.DataSource = getGridViewDataSource();
        gv.EditIndex = e.NewEditIndex;
        gv.DataBind();
    }

    public void OnRowDataBound(Object sender, GridViewRowEventArgs e)
    {
        // convert time display to another format
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // If I comment out this line, then the field is editable, 
            // but the data format is not what I want
            e.Row.Cells[4].Text = process(e.Row.Cells[4].Text);
        }
    }

    public SqlDatasource getGridViewDataSource() {//Customer sql data source}
    public string process(string) {//Customer code}

代码遵循提供的示例 here。问题是,除了改变显示的文本之外,还有什么变化?如果我真的希望它仍然可以编辑怎么办? MSDN 好像没有解释那一点。有人可以帮忙吗?

文章中的示例没有自定义 OnRowEditing 事件。您的函数 gv.DataBind() 触发 OnRowDataBound 两次 - 第一次有填充值,第二次没有填充值(行处于编辑状态)。所以你的函数应该是这样的:

    public void OnRowDataBound(Object sender, GridViewRowEventArgs e)
    {
        // convert time display to another format
        if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState != DataControlRowState.Edit)
        {
            e.Row.Cells[4].Text = process(e.Row.Cells[4].Text);
        }
    }

添加if检查也是一个好主意,但在这种情况下可以没有必要:

    public void OnRowDataBound(Object sender, GridViewRowEventArgs e)
    {
        // convert time display to another format
        if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState != DataControlRowState.Edit)
        {
            if(!string.IsNullOrEmpty(e.Row.Cells[4].Text))
                e.Row.Cells[4].Text = process(e.Row.Cells[4].Text);
        }
    }