如何在 VB.NET 中更新 DataTable 中的一行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/613596/
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
How can I update a row in a DataTable in VB.NET?
提问by Angkor Wat
I have the following code:
我有以下代码:
Dim i As Integer = dtResult.Rows.Count
For i = 0 To dtResult.Rows.Count Step 1
strVerse = blHelper.Highlight(dtResult.Rows(i).ToString, s)
' syntax error here
dtResult.Rows(i) = strVerse
Next
I want to add a strVerse
to the current row.
我想将 a 添加strVerse
到当前行。
What am I doing wrong?
我究竟做错了什么?
回答by JaredPar
The problem you're running into is that you're trying to replace an entire row object. That is not allowed by the DataTable API. Instead you have to update the values in the columns of a row object. Or add a new row to the collection.
您遇到的问题是您试图替换整个行对象。这是 DataTable API 不允许的。相反,您必须更新行对象列中的值。或者向集合中添加一个新行。
To update the column of a particular row you can access it by name or index. For instance you could write the following code to update the column "Foo" to be the value strVerse
要更新特定行的列,您可以按名称或索引访问它。例如,您可以编写以下代码将“Foo”列更新为值 strVerse
dtResult.Rows(i)("Foo") = strVerse
回答by Ken Browning
You can access columns by index, by name and some other ways:
dtResult.Rows(i)("columnName") = strVerse
You should probably make sure your DataTable
has some columns first...
您可能应该DataTable
先确保您有一些列...
回答by vapcguy
Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue
Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.
上面的代码实例化了一个 DataRow。其中“dt”是一个数据表,你可以通过选择任何列来获得一行(我知道,听起来倒退了)。然后,您可以为您想要的任何列设置您想要的任何行的值(我选择了第一行,或“myRow(0)”)。