changing values of a column in datatable in vb.net

Joshua picture Joshua · Jan 20, 2012 · Viewed 40.8k times · Source

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

Answer

Matt Wilko picture Matt Wilko · Jan 20, 2012

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")