vb.net 如何使数据表只读?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14093029/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 11:43:11  来源:igfitidea点击:

How to make a DataTable ReadOnly?

vb.netado.netsqlclient

提问by Joseph Lee

I am writing a function that return a DataTable object. I am using the DataTable.Load( DataReader)to populate the DataTable. However, as I understand it, although the underlying DataReader is ReadOnly, Forward-only; once it is loaded into the DataTable; other programmers can still update the data by DataTable.Rows(x).Column(y).ReadOnly = Falseand then setting the value.

我正在编写一个返回 DataTable 对象的函数。我正在使用DataTable.Load( DataReader)来填充数据表。但是,据我了解,虽然底层的DataReader是ReadOnly,Forward-only;一旦它被加载到数据表中;其他程序员仍然可以通过DataTable.Rows(x).Column(y).ReadOnly = False然后设置值来更新数据。

Is there away to ensure that the DataTable that my function return is ReadOnly? In the older ADODB days, I use the ADODB.LockTypeEnum to mark the returned recordset is readonly.

是否可以确保我的函数返回的 DataTable 是只读的?在较早的 ADODB 时代,我使用 ADODB.LockTypeEnum 来标记返回的记录集是只读的。

By ReadOnly, I mean that the caller to my function (who get the returned DataTable) cannot make changes to the Rows data and/or update it at all (ie, readonly).

通过只读,我的意思是我的函数的调用者(获得返回的数据表)无法更改行数据和/或根本无法更新它(即只读)。

采纳答案by Tim Schmelter

Is there away to ensure that the DataTable that my function return is ReadOnly?

是否可以确保我的函数返回的 DataTable 是只读的?

No, generally there is no such method or way to make it readonly. Unlike the DataViewwhich has the property AllowEditfor this purpose( so you could return a DataView instead).

不,通常没有这样的方法或方法可以使其成为只读。与DataView具有AllowEdit用于此目的的属性不同(因此您可以改为返回 DataView)。

The only way i see to avoid changes on the table is: try to handle the RowChangedevent and call RejectChangesafterwards.

我认为避免更改表的唯一方法是:尝试处理RowChanged事件并在RejectChanges之后调用。

回答by Brad Oestreicher

Another approach to prevent a caller from corrupting your internal DataTable (or DataSet) is to return a copy. Both the DataSet and DataTable classes have a Copy() method that duplicates both the structure and data of the original.

另一种防止调用者破坏内部数据表(或数据集)的方法是返回一个副本。DataSet 和 DataTable 类都有一个 Copy() 方法,可以复制原始结构和数据。

Obviously, this will work better with DataTables containing relatively small amounts of data.

显然,这对于包含相对少量数据的数据表会更好。