web-dev-qa-db-ja.com

位置0のc#データテーブル挿入列

誰もが位置0のデータテーブルに列を挿入する最良の方法を知っていますか?

99
Grant

次のコードを使用して、位置0のDatatableに列を追加できます。

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

Waelの答えを改善し、1行にまとめるためだけに:

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

更新:これは、DataColumnで他に何もする必要がないときに機能することに注意してください。 Add()は問題の列を返し、SetOrdinal()は何も返しません。

85
CigarDoug
    //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
0
Farhad