How to rename a data column name without losing data?

IN:

I want to rename the column names of the data table.

I tried this:

dt.Columns[8].ColumnName = "regnum"; dt.AcceptChanges(); 

but my data is lost after that !!

+6
source share
3 answers
 dt.Columns[8].ColumnName = "regnum"; 

It just binds your Columns[8] to the nonexistent "regnum" column in Db.

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

But I assume that you really want to change Caption:

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

The following is an 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 data loss !!!!!!!! Because it will just change the name of the column.

EDIT

You can also specify the desired column names from stored procedures.

+9
source

Try the following:

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

Source: https://habr.com/ru/post/906384/


All Articles