Thursday, November 2, 2017

How to save data temporarily before permanent saving in database?



Sometimes, we are asked to create a code in such a manner that we have to show the data to the user temporarily and after getting confirmation from user it get saved in the database table. 

To achieve this, we can use data table as a temporary storage to show data to the user. I am presenting logic here to save data temporarily. It is in C# language.

DataTable - DataTable is an in-memory representation of a single database table which has collection of rows and columns. To know more about data table, CLICK HERE.

The code is:
static void Main(string[] args)
        {
            string[] ar = { "John", "Shelly", "Kelly", "Steve" }; // Example Collection
            int i = 0; // we will use it for ID column value
            DataTable dt = new DataTable(); // New Instance of Data Table
            // Adding new columns
            dt.Columns.Add("Id");
            dt.Columns.Add("Name");
            dt.AcceptChanges(); // Save changes
            foreach (string it in ar) // Loop to save data
            {
                i++; // This variable is used to insert ID value with increment
                DataRow dtr = dt.NewRow();
                dtr["Id"] = i;
                dtr["Name"] = it;
                dt.Rows.Add(dtr); // Adding Data row to the data table
                dt.AcceptChanges(); // save changes
            }
            foreach (DataRow dr in dt.Rows) // Loop to display
            {
                Console.WriteLine("Id is {0} and {1}",dr["Id"],dr["Name"]);
            }


        }
Output is:




To delete any data row by indexing, we can use following code-

dt.Rows.RemoveAt(1); // here 1 is index number means second data
To delete data with condition –
for (int j = 0; j < dt.Rows.Count; j++)
           {
               DataRow dr = dt.Rows[j];
               if (Convert.ToInt32(dr["Id"]) == 3) // condition to check record having ID = 3
               {
                    dr.Delete(); // deleting record
               }
               dt.AcceptChanges();
           }
 

Happy Coding

My You Tube Channel – Click Here
Rudra Pratap Singh
Software Engineer

How to Get Organic Views on Your Channel/Content

 Hi Friends, This post will be very short and specific in the information.  If you are a content creator and want some help in getting organ...