.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
Steve Jackman
Imran Ghani
Santhakumar Munuswamy

Home >> Forum >> ADO.Net >> Post New QuestionBookmark and Share Subscribe to Forum

How to add a column in a datatable dynamically....

Posted By: Santosh     Posted Date: November 11, 2010    Points:2   Category :ADO.Net
Hi All,

Any body plz tell me ,
how to add a column in a datatable dynamically in any position...


Ex:i have a datatable called(dt) having 3 columns(ID,Name,DOB)
now i want to add a column called(Salary) dynamically in third position, means after id so my final datataable columns should be
like....

ID,Name,salary,DOB

Regards
Santosh





Responses
Author: Sajid P K             
Posted Date: November 11, 2010     Points: 5   

Hi,

Please use SetOrdinal method of data column...

DataTable.Columns.Add("Salary").SetOrdinal(2)



Regards,
Sajid P k

Author: poptcat             
Posted Date: July 25, 2011     Points: 20   

Take a look at this sample Programatically add DataGridViewComboBoxColumn to DataGridView http://blogcsharp.com/2011/07/c-controls/dynamic-combocolumn/
Line for adding dynamically a column to a DataTable is in the CreateTable method:
Points.Columns.Add(CreateDataColumn("System.String", "PointName", "Point Name", true));

In your case it would be
dt.Columns.Add(CreateDataColumn("System.Int32", "Salary", "Salary", false));


where CreateDataColumn is the following method

DataColumn CreateDataColumn(string colType, string name, string caption, bool readOnly)
{
DataColumn column = new DataColumn();
column.DataType = Type.GetType(colType);
column.ColumnName = name;
column.Caption = caption;
column.ReadOnly = readOnly;
return column;
}


Then you have to use SetOrdinal to specify the position
dt.Columns["Salary"].SetOrdinal[2]





Post Reply

You must Sign In To post reply
 
 
Find more Forum Questions on C#, ASP.Net, Vb.Net, SQL Server and more Here
Quick Links For Forum Categories:
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  OOPs  SilverlightIISJQuery
JavaScript/VBScriptBiztalkWPFPatten/PracticesWCFOthers
www.DotNetSpark.comUnAnsweredAll

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend