views:

780

answers:

3

I have a DataGridView, which is not set to ReadOnly. None of its columns are set to ReadOnly, and the object it is bound to is not set to ReadOnly. Yet, I can't edit the DataGridView items? The .DataSource property of the DataGridView is set to a ReadOnlyCollection<>, but I can programmatically alter the elements, just not from the UI. What's going on?

+3  A: 

It turns out that if your DataGridView is bound to a ReadOnlyCollection, then even though you can programatically edit any item in the collection, the DataGridView will restrict you from changing the values. I'm not sure if this behavior is intentional, but its something to watch out for.

GWLlosa
Cannot reproduce... see below. With ReadOnlyCollection<> none are editable...
Marc Gravell
My bad, it turns out that "the one column that can be changed" was actually not correctly bound to the datasource all along.
GWLlosa
+1 I wish I had searched SO in the morning. This one took me hours of banging my head against the wall before I figured it out.
Rytmis
+1  A: 

This is just an extended comment (hence wiki) in counter to the "the DataGridView will restrict you from changing some values (strings) but not other values (bools)" point; neither is editable; make it a List<T> and both are editable...:

using System;
using System.Collections.ObjectModel;
using System.Windows.Forms;
class Test
{
    public string Foo { get; set; }
    public bool Bar { get; set; }

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        var data = new ReadOnlyCollection<Test>(
            new[] {
                new Test {Foo="abc", Bar=true},
                new Test {Foo="def", Bar=false},
                new Test {Foo="ghi", Bar=true},
                new Test {Foo="jkl", Bar=false},
            });
        Application.Run(
            new Form {
                Text = "ReadOnlyCollection test",
                Controls = {
                    new DataGridView {
                        Dock = DockStyle.Fill,
                        DataSource = data,
                        ReadOnly = false
                    }
                }
            });
    }
}
Marc Gravell
Whoops. Turns out that the "one editable column" was actually a typo in the databinding code, so it was actually "the one editable column that was not actually bound to the data source the entire time.".
GWLlosa
A: 

How are you binding to your DataGridView? One thing is that if you are using a Linq list as the datasource queried from a database and you do not have the complete object, then the properties are readonly unless you specify "with new" in the select function. There is not a lot of information in your post. I hope this helps.

Joseph Connolly