Making a DataGridView column editable after binding it to a BindingList<T>

廉价感情. 提交于 2019-12-24 02:38:12

问题


I have a DataGridView and I'm binding it to a BindingList<KeyValuePair<string, float>>. Here's the relevant part of the code:

        dgv.AutoGenerateColumns = false;

        DataGridViewTextBoxColumn firstColumn = new DataGridViewTextBoxColumn();
        firstColumn.DataPropertyName = "Key";
        firstColumn.HeaderText = "First Column";

        DataGridViewTextBoxColumn secondColumn = new DataGridViewTextBoxColumn();
        secondColumn.DataPropertyName = "Value";
        secondColumn.HeaderText = "Second Column";
        secondColumn.ReadOnly = false;
        secondColumn.ValueType = typeof(float);

        dgv.Columns.Add(firstColumn);
        dgv.Columns.Add(secondColumn);
        dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        dgv.MultiSelect = false;
        dgv.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
        dgv.ReadOnly = false;

        _bindingList = new BindingList<KeyValuePair<string, float>>(_someList);
        dgv.DataSource = _bindingList;

But the second column is still not editable. What should I do to make the second column editable and the first one not?

Edit: I'd like the changes to be reflected on the BindingList instance itself.

Edit 2: I have added this line in the end of the code and now I'm getting an error:

        dgv.Columns[1].ReadOnly = false;

I get this error:

DataGridView column bound to a read-only field must have ReadOnly set to True.

Edit 3: The problem seems to be that I'm using KeyValuePairs in my list.


回答1:


The problem turns out to be that the Key and Value properties of the KeyValuePair class are read-only. The solution is to create a new class that has public setters to represent the data.



来源:https://stackoverflow.com/questions/13234493/making-a-datagridview-column-editable-after-binding-it-to-a-bindinglistt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!