views:

34

answers:

2

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

+1  A: 

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;
digEmAll
Completely agree with digEmAll! Here's the post (http://blogs.msdn.com/b/ericwhite/archive/2009/04/08/why-i-don-t-use-the-foreach-extension-method.aspx) that explains reason for absence of ForEach.
VinayC
@digEmAll: Thx for response with bringing very good knowledge for making me recognize my area of working with Extension Methods. I would take care of these points. But I am a learner in Linq so I would keep using it for few more months until I get complete knowledge about it. I never used IQueryable so I was trying to explore it.
Shantanu Gupta
OK, for IQueryable and IEnumerable differences see for example: http://stackoverflow.com/questions/252785/what-is-the-difference-between-iqueryablet-and-ienumerablet and http://stackoverflow.com/questions/2433306/whats-the-difference-between-iqueryable-and-ienumerable
digEmAll
+1  A: 

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;
MAKKAM