简体   繁体   中英

How to use IQueryable types in DataGridViewColumnCollection in WinForm

I want to set DataGridView's columns to ReadOnly except one or two columns.

I was trying to do this.

dgv.Columns.AsQueryable().ForEach(col=>col.ReadOnly=true); 

But I found that these extension methods are not available at DataGridViewColumnCollection

How can I do the same by this way

The original idea of LINQ is not to modify existing collections, but to return new ones, so methods like ForEach are not among the default LINQ methods.

You could easily write your own ForEach like:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    foreach (var item in source)
        action(item);
}

and so your code would become:

dgv.Columns.Cast<DataGridViewColumn>.ForEach(col=>col.ReadOnly=true); 

BTW...
it is really worthwhile writing it as LINQ extension, when with 2 lines of old imperative-school code you can do the same ?

foreach (DataGridViewColumn col in this.dataGridView1.Columns)
    col.ReadOnly = true;

ForEach method isn't implemented neither in DataGridViewColumnCollection nor in IQueryable interface. Here is the post about it from Eric Lippert's blog.
If you need this functionality you can easily implement extension method

public static void ForEach(this DataGridViewColumnCollection cols, Action<DataGridViewColumn> action)
    {
        foreach (DataGridViewColumn col in cols)
        {
            action(col);
        }
    }

And then use it:

dgv.Columns.ForEach(col => col.ReadOnly = true);

But, I think, it's much more easier just to iterate throw the columns.

foreach (var column in dgv.Columns)
   column.ReadOnly = true;

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