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