How to rename the datatable column name without losing the data?
84,490
Solution 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";
Solution 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.
Author by
Anyname Donotcare
Updated on June 07, 2020Comments
-
Anyname Donotcare almost 4 years
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 !!
-
Anyname Donotcare over 12 yearshmmmm, it is a stored procedure which return data without specific names:like this
(expression) (expression) ....
-
Anyname Donotcare over 12 yearsplease ,Could u explain more what u want to say?