C# 从 DataGridView 解除绑定 BindingSource 的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1547439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way to unbind a BindingSource from a DataGridView
提问by Andy
I have a BindingList<> of objects, set to the DataSource of a BindingSource. This is set to the DataSource of a DataGridView.
我有一个 BindingList<> 对象,设置为 BindingSource 的 DataSource。这被设置为 DataGridView 的数据源。
I'm concerned with not causing any potential memory leaks, so wondering if there is a preferred way to unbind these connections when I am finished with the data.
我担心不会造成任何潜在的内存泄漏,所以想知道在我处理完数据后是否有更好的方法来解除这些连接。
I'm thinking of:
我在想:
datagridview.DataSource = null;
bindingsource.DataSource = null;
bindingsource.Clear();
To re-bind:
重新绑定:
bindingsource.DataSource = bindinglist<myObjects>;
datagridview.DataSource = bindingsource;
Is this order correct, or does it really matter? Have I omitted anything which should be there?
这个顺序是正确的,还是真的很重要?我是否遗漏了应该存在的任何内容?
Any pointers appreciated, thanks.
任何指针表示赞赏,谢谢。
采纳答案by Wael Dalloul
Assigning null to the datagridview DataSource is the best way to clear data source of grid, you are correct.
给datagridview的DataSource赋值null是清除grid数据源的最好方法,你是对的。
回答by Tomas Beblar
If you use custom columns, set AutoGenerateColumns to false before clearing the DataSource. This will ensure your custom columns are preserved. Otherwise they will be cleared and auto generated on the next DataBind.
如果您使用自定义列,请在清除数据源之前将 AutoGenerateColumns 设置为 false。这将确保保留您的自定义列。否则它们将被清除并在下一个 DataBind 时自动生成。
datagridview.AutoGenerateColumns = false;
datagridview.DataSource = null;
Edit: Not sure why this was down voted. This is the correct solution for non auto generated columns. I have the project to prove it. I hope someone finds it useful.
编辑:不知道为什么这被否决了。这是非自动生成列的正确解决方案。我有项目来证明这一点。我希望有人觉得它有用。