问题
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 KeyValuePair
s 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 setter
s to represent the data.
来源:https://stackoverflow.com/questions/13234493/making-a-datagridview-column-editable-after-binding-it-to-a-bindinglistt