How to Save virtually added Gridview records to database



In this article, I am discussing how to save records to database which added virtually to Gridview
It is very simple and here, I am not going to discuss how to connect with database and etc.. .
Above article we have done all of the operation in Gridview like “Add new, Edit, Delete” and this is continuation of those articles.   

First you have to put all the data into DataTable from ViewState[“GrData”] and using “foreach” loop find the rows in your GridView. Check the code……

 protected void saveDetails()
        {
            //calling Model and Property classes
             DetailsModel dmodel = new DetailsModel(connectionString());
             DetailProperty dproperty = new DetailProperty();
            //---------------------------------------------------------------

                    //put all ViewState["GrdData"] to DataTable
                    DataTable dt = (DataTable)ViewState["GrdData"];
      
                        // loop the rows added in Gridview   
                        foreach (GridViewRow row in gdView.Rows)
                         {
                            //find the rows under the column names and assign the value of rows To property
                            dproperty.Name = dt.Rows[row.DataItemIndex]["Name"].ToString();
                            dproperty.Address=dt.Rows[row.DataItemIndex]["Address"].ToString();
                            dproperty.Gender = dt.Rows[row.DataItemIndex]["Gender"].ToString();
                            //calling data insert method  
                                dmodel.insertDetails(dproperty);
                          }
                          //after saving clear the Datatable
                          dt.Clear();
                         //bind the DataTable to GridView  
                         this. gdView.DataSource = dt;
                         this.gdView.DataBind();
          }