0
votes

I am trying to insert column into gridview, I have dropdown below the grid and dropdown is having 10 items now If i select random item assume that I am selecting 8 number item and add clicking add button. this item should create as new column at 8 number in grid.

Suppose grid is not having any column when page is loading and trying to insert column using below code throwing error.

var boundField = new TemplateField { HeaderText = "SelectedProductName"}; grd.Columns.Insert(ddlProduct.SelectedIndex, boundField);

As Selected index can be any random number but grd is throwing out of index error as grid does not have that position.

Could you please help me to insert new column based on selected index from the dropdown.

My goal to achieve to display grid columns as they are listing into the dropdown same sequence.

1

1 Answers

1
votes

First I defined a new class that will help us to store the columname and the index of that column in the dropdownlist:

public MyColumnClass
{

     public MyColumnClass();

     public int DDLindex {get;set;}
     public string ColumnName{get;set;}
}

Here is the main code, each time a new column added, the following code will re-order them, based on their order in the dropdownlist:

 BoundField boundField = new BoundField();
 boundField.DataField = drp_Items.SelectedItem.Text;
 boundField.Headertext = "Item";

 myGridView.Columns.Insert(0, boundField);

 //this list will store the existing 
 List<MyColumnClass> columnList = new List<MyColumnClass>();

 for(int x = 0; x < myGridView.Columns.Count; x++)
 {
      //dropdownlist index of the column
      var a = drp_Items.Items.IndexOf(drp_Items.Items.FindByValue(myGridView.Columns[x].DataField)); 
      MyColumnClass column = new MyColumnClass();
      column.DDLindex = a;
      column.ColumnName= myGridView.Columns[x].DataField;

      columnList.Add(column);
 }

 /the column list is created above, now we can clear the existing columns, and regenerate with the correct order
 myGridView.Columns.Clear();
 foreach(MyColumnClass item in columnList.OrderBy(c => c.DDLindex))//we order the list based on DDLindex
 {
      BoundField boundField = new BoundField();
      boundField.DataField = item.ColumnName;
      boundField.Headertext = "Item";

      myGridView.Columns.Add(boundField);

 }

P.S. You should make autogeneratecolumns="false" if you are binding data to Gridview.