20 November 2012

Update Datatable in C#


// Update Datatable in C#

//Two methods to Update Datatable in C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace DataTableUpdation
{
    public partial class _Default : System.Web.UI.Page
    {
     
     
        protected void Page_Load(object sender, EventArgs e)
        {


            try
            {
                DataTable dt = new DataTable();
                //Add Datacolumn
                DataColumn workCol = dt.Columns.Add("FirstName", typeof(String));

                dt.Columns.Add("LastName", typeof(String));
                dt.Columns.Add("Blog", typeof(String));
                dt.Columns.Add("City", typeof(String));
                dt.Columns.Add("Country", typeof(String));

                //Add in the datarow
                DataRow newRow = dt.NewRow();

                newRow["firstname"] = "Arun";
                newRow["lastname"] = "Prakash";
                newRow["Blog"] = "http://royalarun.blogspot.com/";
                newRow["city"] = "Coimbatore";
                newRow["country"] = "India";

                dt.Rows.Add(newRow);

   

              // 1st method
                // Get all DataRows where the name is the name you want.
                IEnumerable< DataRow > rows = dt.Rows.Cast< DataRow >().Where( r => r["firstname"].ToString() == "Arun");
                // Loop through the rows and change the name.
                rows.ToList().ForEach(r => r.SetField("firstname", "AnotherName"));

                // 2nd method
                // Alternative approach.
                // Simply loop through the rows, check the value of the Name field and change its value accordingly.
                foreach (DataRow row in dt.Rows)
                {
                    if (row["firstname"].ToString() == "AnotherName")
                        row.SetField("firstname", "Arun");
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }


        }

    }
}





No comments:

Post a Comment

Comments Welcome

Finding duplicate records in SQL Server

 Finding duplicate records in SQL Server 1. The GROUP BY and HAVING Method This is the most standard approach. It is best used when you on...