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
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
go with the loop like
for (i = 2; i < grdview.columns.count; i ++)
{
grdview.columns[2].remove();
}
It is untested code. please check it.
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, i.e. 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();
}
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;
You can use following code:
while(grid.Columns.Count > 2)
{
Grid.Columns.RemoveAt(grid.Columns.Count - 1);
}
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;
}