c#datatable在位置0插入列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1339880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:19:47  来源:igfitidea点击:

c# datatable insert column at position 0

c#datatableinsertposition

提问by Grant

does anyone know the best way to insert a column in a datatable at position 0?

有谁知道在位置 0 的数据表中插入一列的最佳方法吗?

采纳答案by Wael Dalloul

You can use the following code to add column to Datatable at postion 0:

您可以使用以下代码将列添加到位置 0 的数据表:

    DataColumn Col   = datatable.Columns.Add("Column Name", System.Type.GetType("System.Boolean"));
    Col.SetOrdinal(0);// to put the column in position 0;

回答by CigarDoug

Just to improve Wael's answer and put it on a single line:

只是为了改进 Wael 的答案并将其放在一行中:

dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);

UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.

更新:请注意,当您不需要对 DataColumn 执行任何其他操作时,这会起作用。Add() 返回有问题的列, SetOrdinal() 不返回任何内容。

回答by Farhad

    //Example to define how to do :

    DataTable dt = new DataTable();   

    dt.Columns.Add("ID");
    dt.Columns.Add("FirstName");
    dt.Columns.Add("LastName");
    dt.Columns.Add("Address");
    dt.Columns.Add("City");
           //  The table structure is:
            //ID    FirstName   LastName    Address     City

       //Now we want to add a PhoneNo column after the LastName column. For this we use the                               
             //SetOrdinal function, as iin:
        dt.Columns.Add("PhoneNo").SetOrdinal(3);

            //3 is the position number and positions start from 0.`enter code here`

               //Now the table structure will be:
              // ID      FirstName   LastName    LastName   PhoneNo     Address     City