Change DataTable column value based on condition in C# and VB.Net

Last Reply 5 months ago By pandeyism

Posted 5 months ago

Hi 

I need to loop a datatable and make some value change so i decided to copy that table to another new one.

    private DataTable EditTable(DataTable dataTable)
    {
        var newTable = new DataTable();
        newTable = dataTable.Copy();
        foreach (DataRow row in newTable.Rows)
        {
            if (row[0].ToString().Length == 3)
                row[0] = "00" + row[0].ToString();
        }
        return newTable;
    }

That method not works, the first column has same value of first datatable

Posted 5 months ago

Hi jon,

Refer below sample.

Namespaces

C#

using System.Data;

VB.Net

Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(string)),
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Country",typeof(string)) });
        dt.Rows.Add("1", "John Hammond", "United States");
        dt.Rows.Add("2", "Mudassar Khan", "India");
        dt.Rows.Add("003", "Suzanne Mathews", "France");
        dt.Rows.Add("4", "Robert Schidner", "Russia");
        DataTable newTable = dt.Copy();
        foreach (DataRow row in newTable.Rows)
        {
            if (row[0].ToString().Length == 3)
            {
                row[0] = "00" + row[0].ToString();
            }
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As DataTable = New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(String)), New DataColumn("Name", GetType(String)), New DataColumn("Country", GetType(String))})
        dt.Rows.Add("1", "John Hammond", "United States")
        dt.Rows.Add("2", "Mudassar Khan", "India")
        dt.Rows.Add("003", "Suzanne Mathews", "France")
        dt.Rows.Add("4", "Robert Schidner", "Russia")
        Dim newTable As DataTable = dt.Copy()

        For Each row As DataRow In newTable.Rows

            If row(0).ToString().Length = 3 Then
                row(0) = "00" & row(0).ToString()
            End If
        Next
    End If
End Sub

Screenshot