How to save data from Dynamic DataTble object to database c#.Net

    Dynamic DataTable to SQL Server c#.Net:
   This article will resolve you how to save the data from dynamic datatable to the database.First thing is the datatable will have the datarows. So you have to save the values from that data rows to the database. The datatable will have multiple rows so you have to run a loop to save all the rows data to SQL database. If you want to see the data of the dataTable object bind the DataTable object to the DataGridView control.

Creating DataTabe and Columns:

        DataTable tblname = new DataTable();
        tblname .Columns.Add("ProductID", typeof(int));
        tblname .Columns.Add("ProductName", typeof(string));
        tblname .Columns.Add("ProductCompany", typeof(string));

    This code will create a datatable with column names ProductID ,ProductName and ProductCompany. To save the data from these datatable we have to write the foreach loop and have to insert the datarows data to database columns.

Event: Write this code in btnSave_Click event.

    SqlConnection cn = new SqlConnection(@"Data Source=CENSYS10\SQLEXPRESS;
   Integrated Security=true;Initial Catalog=workshop");
   cn.Open();

        foreach (DataRow dr in dt.Rows)
         {
             SqlCommand cmd = new SqlCommand("insert into treetable(P_Id,P_Name,P_Company) values(@PId,@PName,@PCom)",cn);
             cmd.Parameters.AddWithValue("@PId",dr["ProductID"]);
             cmd.Parameters.AddWithValue("@PName", dr["ProductName"]);
             cmd.Parameters.AddWithValue("@PCom", dr["ProductCompany"]);
             cmd.ExecuteNonQuery();
             MessageBox.Show("DataTable saved successfully.");
          }


    This code will save the datatable data to the database columns names P_Id,P_Name and P_Company.  
 How to see the data of the DataTable:
    To see the data from the table bind it to DataGridView control.For that take dataGridView control
 from the Toolbox.Write the code in SeeDatabutton Click event. 

 dataGridView1.DataSource=dt;

I hope this code will help you.

No comments:

Post a Comment