DataGridView无法编辑单元格(修改无法保存)问题求助
解决DataGridView绑定结构体List无法编辑的问题
兄弟,你遇到的这个问题根源很明确——你用了值类型的struct来绑定DataGridView,而不是引用类型的class。
为什么结构体不行?
struct是值类型,当你把它放进BindingList里时,每次DataGridView获取数据、或者你编辑单元格时,操作的都是结构体的副本。你在单元格里修改的只是这个临时副本的值,退出编辑模式后,副本被丢弃,原List里的结构体完全没变化,所以单元格就自动恢复成原来的内容了。
解决方案:把结构体改成类
这是最直接也最推荐的做法,因为class是引用类型,BindingList里存储的是对象的引用,你编辑单元格时修改的是原对象的属性值,修改会直接同步回List中。
修改后的代码示例:
public class singleFieldFrame : INotifyPropertyChanged { private string id; private string text; // 如果需要允许编辑ID,就加上setter;不需要的话可以保留只读 public string id_p { get { return id; } set { if (id != value) { id = value; OnPropertyChanged(nameof(id_p)); } } } public string text_p { get { return text; } set { if (text != value) { text = value.Replace('\0', ';'); OnPropertyChanged(nameof(text_p)); } } } public singleFieldFrame(string frameID, string data) { id = frameID; text = data.Replace('\0', ';'); } // 实现INotifyPropertyChanged接口,让DataGridView实时感知属性变化 public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
额外说明
- 实现
INotifyPropertyChanged接口不是必须的,但加上它之后,当你在代码里直接修改singleFieldFrame对象的属性时,DataGridView会自动刷新显示,体验更流畅。 - 如果你真的不想改成
class(非常不推荐),那你需要在单元格编辑结束后,手动把修改后的结构体对象替换回BindingList对应的位置,但这种做法繁琐且容易出错,远不如用class省心。
内容的提问来源于stack exchange,提问作者Maxim Voloshin
相关产品推荐
相关产品推荐

