开发者

How to remove datatable column in c#

i have an datatable with 12 columns.now i need to remove all the columns开发者_运维百科 except at the position "0"

i can remove individually by specifying the columns name. but i dnt want to do that.as it is not best way to code.

is there any other i can do that

thanks


Go backwards through the columns and remove each one. You have to go backwards to avoid an index out of range exception.

// index should include zero
for( int index=table.Columns.Count-1; index>=0; index-- )
{
   table.Columns.RemoveAt( index );
}

VB.Net Lovers:

'index should include zero
For index As Integer = table.Columns.Count - 1 To 0 Step -1
    table.Columns.RemoveAt(index)
Next


while(myDataTable.Columns.Count > 1)
{
    myDataTable.Columns.RemoveAt(myDataTable.Columns.Count - 1);
}


The code you can take down the columns from a Data table object. What my code does is it will loop through the Data table objects and then remove the columns one by one.

    String strcolname = "";
    int i=0;
    //Get Data for the reader object
    using (reader = cmd.ExecuteReader())
    {  
    // Load the Data table object
    dataTable.Load(reader);

    //Loop thorough the DataTable object
    for (i=dataTable.Columns.Count-1;i>=0;i--)
    {

    /* 
    To be more precise , specify the column name you dont want to get    deleted, 
    (you can add multilple column names here)*/

    strcolname = dataTable.Columns[i].ColumnName.ToString();

     if (strcolname != "ABCD")
     {
      dataTable.Columns.RemoveAt(i);
     }
    }    
   }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜