Any way to manipulate the columns in GridView with AutoGenerateColumns = true?

前端 未结 5 475
谎友^
谎友^ 2020-12-11 17:42

It seems like there\'s no way to manipulate the columns of a Gridview if AutoGenerateColumns = true. Here\'s my scenario:

I\'ve got a generic GridView that displays

5条回答
  •  悲&欢浪女
    2020-12-11 18:10

    Building on the accepted answer, a dictionary can be created to map from column names to column indicies in the RowDataBound event to allow use of header names. Also a column swap is shown.

    Dictionary _columnIndiciesForAbcGridView = null;
    
    protected void detailsReportGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (_columnIndiciesForAbcGridView == null)
        {
            int index = 0;
            _columnIndiciesForAbcGridView = ((Table)((GridView)sender).Controls[0]).Rows[0].Cells
                .Cast()
                .ToDictionary(c => c.Text, c => index++);
        }
    
        // Add a column, this shifts the _columnIndiciesForAbcGridView though.
    
        TableCell cell = new TableCell();
        cell.Text = "new Column";
        e.Row.Cells.AddAt(2, cell);
    
        // Swap 0 and 1
    
        int c0 = _columnIndiciesForAbcGridView["ConfigId"];
        int c1 = _columnIndiciesForAbcGridView["CreatedUtc"];
    
        string text = e.Row.Cells[c0].Text;
        e.Row.Cells[c0].Text = e.Row.Cells[c1].Text;
        e.Row.Cells[c1].Text = text;
    }
    

提交回复
热议问题