How to rename the datatable column name without losing the data?

Q:

I want to rename my data table column names .

I tried this :

dt.Columns[8].ColumnName = "regnum";

dt.AcceptChanges();

but my data is lost after that !!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

dt.Columns[8].ColumnName = "regnum";

This just binds your Columns[8] to the non-existing “regnum” column in the Db.

If you want to rename the actuals Db column, execute an SQL script.

But my guess is you actually want to change the Caption:

  dt.Columns[8].Caption = "regnum";

Method 2

Following is the example:

DataTable Dt = new DataTable();
DataColumn Dc = new DataColumn("Name");
DataColumn Dc1 = new DataColumn("ID");
Dt.Columns.Add(Dc);
Dt.Columns.Add(Dc1);

DataRow dr = Dt.NewRow();
dr["name"] = "1";
dr["ID"] = "111";
Dt.Rows.Add(dr);

dr = Dt.NewRow();
dr["name"] = "2";
dr["ID"] = "11112";
Dt.Rows.Add(dr);

Dt.Columns[0].ColumnName = "ddsxsd";
Dt.AcceptChanges();

I did not find any data loss!!!!!!!! Because it will merely change the column name.

EDIT

You can also bring your desired column names from your Stored Procedures.

Method 3

Try this:

 dataTable.Columns["ExistingColumnName"].ColumnName = "regnum";

Method 4

Also may this code serve someone!
I have a realize that this is the easiest way just like @Henk said:

using (SqlDataAdapter da = new SqlDataAdapter())
                    {
                        DataTable dt = new DataTable();
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        da.SelectCommand = cmd;
                        da.Fill(dt);
                        dt.Columns[0].ColumnName = "Item NO";
                        dt.Columns[1].ColumnName = "LocalCode";                       
                        dt.Columns[2].ColumnName = "Currency";
                        dt.Columns[3].ColumnName = "Menu Flag";
                        dt.Columns[4].ColumnName = "Item Class";
                        dt.Columns[4].ColumnName = "Dress Sort";
                        return dt;
                    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x