簡體   English   中英

更改OnRowDataBound事件中的文本后,asp 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}

該代碼遵循此處提供的示例。 問題是,除了改變顯示的文字外,還有什么改變? 如果我真的希望它仍可編輯怎么辦? 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 check也是一個好主意,但是在這種情況下可能沒有必要:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM