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

时间:2015-03-18 15:28:36

标签: c# gridview asp-classic rowdatabound

我使用GridView显示并允许修改数据。但是不是直接使用数据库中的数据,而是必须转换它们(考虑在不同的日期格式之间切换),因此在RowDataBound事件中我更新了一列的Text字段。但是,捕获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似乎没有解释那一点。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

在文章的示例中,没有自定义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);
        }
    }
相关问题