ExtensionMethod.NET Home of 819 C#, Visual Basic, F# and Javascript extension methods

RenameColumn

Rename a code that allows only stating the current name column and a new name.

Source

public static void RenameColumn(this System.Data.DataTable dt, string oldName, string newName)
{
    if (dt != null && !string.IsNullOrEmpty(oldName) && !string.IsNullOrEmpty(newName) && oldName != newName)
    {
        int idx = dt.Columns.IndexOf(oldName);
        dt.Columns[idx].ColumnName = newName;
        dt.AcceptChanges();
    }
}

Example

// Consider that dataSetName is the DataSet that contains a DataTable
dataSetName.Tables[0].RenameColumn("Column1", "Name");
dataSetName.Tables[0].RenameColumn("Column2", "Email");
dataSetName.Tables[0].RenameColumn("Column3", "RegistrationDate");

Author: Raphael Augusto Ferroni Cardoso

Submitted on: 4 jun 2014

Language: C#

Type: System.Data.DataTable

Views: 2988