Click here to Skip to main content
15,896,912 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to add a column to a database permanently using Datatable I expect something like this

C#
Projects.connection = new OleDbConnection(Projects.connectionstring);
         Projects.connection.Open();
         Projects.da = new OleDbDataAdapter(Projects.cmdstring, Projects.connection);
         Projects.dt = new DataTable();
         Projects.da.Fill(Projects.dt);
         Projects.dt.Columns.Add("new column name");
         Projects.cmdb = new OleDbCommandBuilder(Projects.da);


                 Projects.dt.GetChanges();



                 if (Projects.dt.GetChanges() != null)
                 {

                     Projects.da.Update(Projects.dt);
                     Projects.connection.Close();

                 }
                 Projects.dt.AcceptChanges();


but unfortunately new column is not added in the database, please somebody help.

thanks in advance
Posted

Unfortunately things do not work that way. You will have to use an ADO.NET[^] Command Object[^] (for example an SqlCommand[^]).
You will have to make a query that correctly inserts the column in your database table. The code for this is dependent on the type of database you are using. Pass this to the SqlCommand, together with a Connection Object and run the query. Be sure you can only do this once though. Every next time you try to run the command an Exception will be thrown that the Column already exists.
For this reason it is actually always better to have your columns defined at design time, because if you REALLY don't know if you have the column or not all code you write should have to work with AND without that column.
Pseudo code for your problem:
C#
if !(CheckIfMyColumnExists){
OleDbCommand cmd = new OleDbCommand("alter table MyTable add MyColumn int", myConn);
cmd.ExecuteNonQuery();
}
// Column should exist at this point.
 
Share this answer
 
Comments
[no name] 29-Oct-11 15:01pm    
thanks a lot for the reply. I agree that during the design time itself the column should be defined. but I want to give a provision to change the column name during execution stage as and when it is required.

is it possible to use OleDb commands. because I am not using sqlCommands.

can you just give me a sample.
Sander Rossel 29-Oct-11 15:36pm    
OleDbCommand, SqlCommand... Works exactly the same except you replace Sql with OleDb (see my code example!)... Keep in mind that changing a column name is very dangerous because reports may break, code may break, anything that uses a column name rather than index may break!
[no name] 30-Oct-11 1:49am    
thank you
Sander Rossel 30-Oct-11 6:28am    
No problem. Don't forget to vote/accept the answer that helped you :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900