更改 vb.net 中数据表中列的值

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

changing values of a column in datatable in vb.net

vb.netdatasetdatarowdatacolumn

提问by Joshua

I want to loop through a databale and change the values of a specific column in that datatable.

我想遍历一个数据包并更改该数据表中特定列的值。

eg: the database returns Request_ID, Desc, Dateand Status_Ind. The Status_Indcolumn contains integer values. I dont want to show the integer values to the user. I want to convert that to a string value based on the integer values returned in that columns.

例如:数据库恢复Request_IDDescDateStatus_Ind。该Status_Ind列包含整数值。我不想向用户显示整数值。我想根据该列中返回的整数值将其转换为字符串值。

if Status_Ind = 1 then 
    'the values changes to Published

回答by Matt Wilko

Assuming your DataTable is defined as this:

假设您的 DataTable 定义为:

Dim dt As DataTable

First you need to add a new column to your DataTable to hold the Status:

首先,您需要向 DataTable 添加一个新列以保存状态:

dt.Columns.Add("Status", Type.GetType("System.String"))

Now Loop through the DataTable and update the status column:

现在循环遍历数据表并更新状态列:

For Each dr As DataRow In dt.Rows
    Select Case CInt(dr.Item("Status_Ind"))
        Case 1
            dr.Item("Status") = "Published"
        Case 2
            dr.Item("Status") = "Some other Status"
        Case Else
            dr.Item("Status") = "Unknown"
    End Select
Next

Then you could then remove the integer column:

然后你可以删除整数列:

dt.Columns.Remove("Status_Ind")

回答by alundy

You could do it by creating another column:

您可以通过创建另一列来做到这一点:

Dim dt As New DataTable
dt.Columns.Add(New DataColumn("status_int", GetType(Int32)))
dt.Columns.Add(New DataColumn("status_str", GetType(String)))

'add example row - not publised
Dim newDr0 As DataRow = dt.NewRow
newDr0(0) = 0
dt.Rows.Add(newDr0)

'add example row - publised
Dim newDr1 As DataRow = dt.NewRow
newDr1(0) = 1
dt.Rows.Add(newDr1)

For Each dr As DataRow In dt.Rows
    Select Case dr(0)
        Case 1
            dr(1) = "Published"
        Case Else
            dr(1) = "Not published"
    End Select
Next

For Each dr In dt.Rows
    Console.WriteLine(dr(0).ToString + " " + dr(1).ToString)
Next