简体   繁体   English

如何清除大于索引1的GridView列

[英]How to clear the GridView column greater than index 1

how to clear the GridView column greater than index 1. 如何清除大于索引1的GridView列。

grdview.Columns.Clear() will clear all columns, but i need to clear the columns greater than index 1 grdview.Columns.Clear()将清除所有列,但我需要清除大于索引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. 我相信您正在使用ASP.NET做到这一点。 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. 我不是C#程序员,但我假设像在Delphi(相同的语言架构师)中那样,集合是基于0的。 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). 如果从2删除到gridView.Columns.count-1,那么您将不会删除所有列,因为在删除列时它们会移位,即,在第一次删除第二列之后,第三列现在是第二列,但是下一个删除的列将是第三列(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. 隐藏列比删除列更容易,因为删除枚举元素会导致枚举数被重置,因此您需要执行加法操作来考虑这种行为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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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