问题
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
, Date
and Status_Ind
. The Status_Ind
column 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.
if Status_Ind = 1 then
'the values changes to Published
回答1:
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
回答2:
Assuming your DataTable is defined as this:
Dim dt As DataTable
First you need to add a new column to your DataTable to hold the Status:
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")
来源:https://stackoverflow.com/questions/8939398/changing-values-of-a-column-in-datatable-in-vb-net