简体   繁体   中英

Insert record from c# datatable to a database

I have this datatable, actually a list of datatable List<DataTable> lstDataSource , now for each table in the list I know there are exactly 6 rows, (monday to saturday!), but there can be any number of columns (well from 6 to 14 that is, the number of hours an employee is working per day!) So I know the limits of both rows and columns in each datatable. My point is how do I use this list of datatable to update (rather insert) all these values in read database table EmpWorkSchedule . What I know is total rows inserted would be lstDataSource.Count * 6 right? Also, for any column that doesn't have values, (some employee work 6 hrs, some 7 hrs etc... ) other columns in that rows would be just set to null. (They are defined as nullable in database). I hope I madeself clear. So, how can I do this?
Also, if there's anything unclear, please feel free to ask.

EDIT : I have this list of DataTable List<DataTable> lstDataTable , what I want is to insert all rows from each of these tables in the list, to a database table named EmpWorkSchedule , all the values in each row are sequential, that is first column corresponds to column 1 in database table, and so on, okay? But now all rows have values for all column, some have 6, some 7, some 8.. What I want is that for the columns, for which, there is no value in the datarow, should be left null in the database table, rest all values should be inserted.

Also, using an adapted doesn't seems likely because its used with select, I am not selecting anything, I am inserting something.

Maybe you just need to Loop on your DataTable and save each row records on your DB Something Like:

Your DataTable

Col1 |  Col2
abc  |  456 
def  |  789

On Your Code Behind do something like:

foreach(DataRow row in YourDataTable.Rows)
{

  string myColumn1  = row["Col1"].ToString();  
  int mycolumn2 =  Convert.ToInt32(row["Col2"]);

  //Your Insert Statement
  //First Loop you will get  
  //myColumn1 = abc and myColumn2=456
  //2nd loop will be def and 789

}

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM