简体   繁体   中英

How to clear the GridView column greater than index 1

how to clear the GridView column greater than index 1.

grdview.Columns.Clear() will clear all columns, but i need to clear the columns greater than index 1

You can use following code:

while(grid.Columns.Count > 2)
{
    Grid.Columns.RemoveAt(grid.Columns.Count - 1);
}

I believe you're working with ASP.NET this will do. However, I would like to know why you want to remove the column. I could give you a better solution.

foreach(DataGridColumn col in vGrid.Columns)
{
     col.Visible = false;
}

vGrid.Columns[0].Visible = true;
vGrid.Columns[1].Visible = true;

or if you are using a template field

foreach(TemplateField col in vGrid.Columns)
{
    col.Visible = false;
}

vGrid.Columns[0].Visible = true;
vGrid.Columns[1].Visible = true;
for (i = 2; i < gridView.Columns.count; i ++)
{
   gridView.Columns[i].Remove();
}  

Correction

    while(gridView.Columns.count>2)
    {
    gridView.Columns.RemoveAt(2);
    //Or gridView.Columns.RemoveAt(gridView.Columns.Count -1);
    }

I am no C# programmer, but I assume that as in Delphi (same language architect) collections are 0 based. therefore

for (i = gridView.Columns.count - 1; i > 1; i --)
{
   gridView.Columns[i].Remove();
}  

If you remove from 2 to gridView.Columns.count - 1 then you will not remove all columns, as they get shifted when a column is removed, ie after the first remove of column two, the column that was third is now second, but the next column removed will be the third (i = 3).

Alternative:

while (gridView.Columns.Count > 2) 
{

   gridView.Columns[gridView.Columns.Count - 1].Remove();
}  

go with the loop like

for (i = 2; i < grdview.columns.count; i ++)
{
   grdview.columns[2].remove();
}  

It is untested code. please check it.

It's easier to hide columns rather than to remove, because removing an element of enumeration causes the enumerator to be reseted so you need to do an addition operation to consider such behavior, IMO.

using System.Linq;

GridView1.Columns
    .OfType<DataControlField>()
    .Where(c => GridView1.Columns.IndexOf(c) > 1)
    .ToList()
    .ForEach(c => c.Visible = false);

or

foreach(var c in GridView1.Columns
                              .OfType<DataControlField>()
                              .Where(c => GridView1.Columns.IndexOf(c) > 1))
{
    c.Visible = false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM