Vishal Torne
Vishal Torne

Reputation: 366

moving columns in gridview between template fields and bound fields

I have a gridview (GridviewProduct) in that i Have a Template field column Link button as Remove From Cart and and another Template Field column next to it as Quantity and other three Fields are boundField like ProductName, ProductPrice and ProductBrand. Which Looks as Follows: enter image description here

I want to move the quantity column to the end of the gridview at the right hand side. when i use this code it gives me an error:

Insertion index was out of range

 var Quantity = GridViewProduct.Columns[1];
 GridViewProduct.Columns.RemoveAt(1);
 GridViewProduct.Columns.Insert(5, Quantity);

please help.

Upvotes: 0

Views: 1426

Answers (2)

kundan
kundan

Reputation: 73

your requirement can be achieved in Gridview's RowCreated event

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            GridViewRow row = e.Row;
            List<TableCell> columns = new List<TableCell>();

            //Get the first Cell /Column
            TableCell cell = row.Cells[1];
            // Then Remove it after
            row.Cells.Remove(cell);
            //And Add it to the List Collections
            columns.Add(cell);

            // Add cells
            row.Cells.AddRange(columns.ToArray());
        }

Upvotes: 1

AGuyCalledGerald
AGuyCalledGerald

Reputation: 8150

If you have 5 columns and remove one of them, you have 4 left. The index of a new last column would than be 4 (since it is zero-based).

GridViewProduct.Columns.Insert(4, Quantity);

I am not sure if this removes all problems, but at least this error should go...

Upvotes: 1

Related Questions