Articles in this section
Category / Section

How to connect and update changes from Gantt to SQL database

4 mins read

In Gantt, we can load data from SQL database and can update the changes to the SQL database. SQL database connection in Gantt can be established by using `connectionStrings` tag in the web.config file. Please refer following code snippet for adding SQL connection in web.config

<connectionStrings> 
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\GanttDataSource.mdf" /> 
  </connectionStrings> 
 

 

CRUD actions performed in Gantt data can be updated to SQL database using the client side event ActionComplete and with AJAX post method. The event argument  requestType of the ActionComplete client side event is used to identify the type of action performed in Gantt such as update, delete, add new task. Please refer the below code example for updating the changes to the SQL database.

 

@(Html.EJ().Gantt("Gantt")
    .Datasource(ViewBag.dataSource)
    .ClientSideEvents(eve => {
        eve.ActionComplete("ActionComplete");
    }).
    //...
)@(Html.EJ().ScriptManager())

 

 

<script type = "text/javascript">
 
    // To update the database through dialog editing or tool bar editing
    function ActionComplete(args) {
 
        if (args.requestType === 'save' && args.addedRecord) {
            //Newly Added Record is obtained here , which can be updated to database
            var ganttRecord = args.addedRecord.item;
            if (args.addedRecord.parentItem)
                ganttRecord["ParentId"] = args.addedRecord.parentItem.taskId;
            $.ajax({
                type: "POST",
                url: "/Gantt/Add", //Add is Server side method
                data: ganttRecord,
                dataType: "json"
 
            });
            if (args.updatedRecords && args.updatedRecords.length)
                  updateRecords(args.updatedRecords);
 
        } else if (args.requestType === 'delete') {
            var data = args.data;
            var ganttRec = data.item;
            $.ajax({
                type: "POST",
                url: "/Gantt/Delete", //Delete is Server side method
                data: ganttRec,
                dataType: "json"
            });
 
            if (data.hasChildRecords) {
                deleteChildRecords(data);
            }
            if (args.updatedRecords && args.updatedRecords.length)
                updateRecords(args.updatedRecords);
        }
 
        // To update the database during Outdent,editing,indent,predecessor update operation
        else if (args.requestType == "indent" || args.requestType == "outdent" || args.requestType == "recordUpdate" || (args.requestType === 'save' && args.modifiedRecord)) {
             var ganttRec = [];
             if (args.requestType == "save")
                 ganttRec.push(args.modifiedRecord);
             else
                 ganttRec.push(args.data);
             if (args.updatedRecords && args.updatedRecords.length)
                 ganttRec = ganttRec.concat(args.updatedRecords);
             updateRecords(ganttRec);
        }
        else if (args.requestType == "dragAndDrop") {
                var ganttRec = [];
                ganttRec.push(args.draggedRow);
                if (args.updatedRecords && args.updatedRecords.length)
                    ganttRec = ganttRec.concat(args.updatedRecords);
                updateRecords(ganttRec);
            }
 
    }
 
//Delete inner level child records
function deleteChildRecords(record) {
    var childRecords = record.childRecords,
        length = childRecords.length,
        count, currentRecord;
    for (count = 0; count < length; count++) {
        currentRecord = childRecords[count];
        $.ajax({
            type: "POST",
            url: "/Gantt/Delete", //Delete is Server side method
            data: currentRecord.item,
            dataType: "json"
        });
 
        if (currentRecord.hasChildRecords) {
            deleteChildRecords(currentRecord);
        }
    }
} 
 
 
        //update the record
        function updateRecords(records) {
            var updateRecord = [];
            if (records && records.length) {
                var length = records.length;
                for (var i = 0; i < length; i++)
                    updateRecord.push(records[i].item);
            }
            $.ajax({
                type: "POST",
                url: '/Gantt/Update', //Update is Server side method
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(updateRecord),
                dataType: "json",
            })
        }
</script>

Controller Code [C#]:

 

Creating Gantt object

public class GanttData
        {
        public string TaskId { get; set; }
        public string TaskName { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }     
        public string ParentId { get; set; }
        public string Duration { get; set; }        
        public string Progress { get; set; }
        public List<string> ResourceID { get; set; }
        public string Predecessor { get; set; }
        }
 
public class GetResource
    {
        public string value { get; set; }
        public string text { get; set; }
    }

Connecting SQL database and fetching records from database:

    public class GanttController : Controller
    {
 
        public ActionResult Index()
        {
 
            ViewBag.dataSource = GetGanttdata();
            var Resource = GetResourceData();
            ViewBag.resource = Resource;
            return View();
         }
         
         public List<GanttData> GetGanttdata()
        {
            List<GanttData> list = new List<GanttData>();
            SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);//connectionString
            con.Open();
 
            using (con)
            {
                using (var command = con.CreateCommand())
                {
                    command.CommandText = "SELECT * FROM GanttData1";
 
                    using (var reader = command.ExecuteReader())
                    {
                        var indexOfCol1 = reader.GetOrdinal("TaskId");
                  //…
                        var indexOfCol6 = reader.GetOrdinal("ParentId");
                        
                        while (reader.Read())
                        {
                            GanttData obj = new GanttData();
                            obj.TaskId = reader.GetValue(indexOfCol1).ToString();
                  //…
                            obj.ResourceID = this.GetResourceValues(reader.GetValue(indexOfCol8).ToString());
                        }
                        reader.Close();
                    }
                }
                con.Close();
            }
            return list;
        }   
           

Add method to add new tasks to SQL database:

        public ActionResult Add(GanttData Task)
        {
 
            //Here Task is the added New Task
            //Add Task 
            //Using INSERT Query to add the New Record to SQL Table
 
            string cmdString = "INSERT INTO GanttData1 ([TaskName],[ParentId],[TaskId],[Predecessor],[StartDate],[EndDate],[Progress],[Resource],[Duration])" + "VALUES(@TaskName,@ParentId,@TaskId,@Predecessor,@StartDate,@EndDate,@Progress,@Resource,@Duration)";
 
            SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);//connectionString
 
            con.Open();
           
            using (SqlCommand sqlCommand = new SqlCommand(cmdString, con))
            {
                sqlCommand.Parameters.AddWithValue("@TaskId", Task.TaskId);
 
 //…
                sqlCommand.Parameters.AddWithValue("@Progress", Task.Progress);
                
                if (Task.ResourceID == null)
                {
                    sqlCommand.Parameters.AddWithValue("@Resource", Task.ResourceID).Value="";
                }
                else
                {
                    var ResourceList = this.GetResourceValues(string.Join(",", Task.ResourceID.ToArray()));
                    sqlCommand.Parameters.AddWithValue("@Resource", string.Join(",", ResourceList.ToArray()));
                }
                
                if (Task.ParentId == null)
                {
                    sqlCommand.Parameters.AddWithValue("@ParentId", Task.ParentId).Value = "";
                }
                else
                {
                    sqlCommand.Parameters.AddWithValue("@ParentId", Task.ParentId);
                }              
                int test = sqlCommand.ExecuteNonQuery();
            }
 
            con.Close();
 
// Return as JSON object to the client side
            return Json(Task, JsonRequestBehavior.AllowGet);
           }

Update method to update the changes from Gantt to SQL database:

        [HttpPost()]
        public ActionResult Update(List<GanttData> Tasks)        {
            //Update Edited TaskDetails
            //Using UPDATE SQL Query to Save the Modified taskData into the Table           
 
            SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);//connectionString
 
            con.Open();
            foreach (GanttData Task in Tasks)
            {
                string IDNumber = Task.TaskId;
 
                string cmdString = "UPDATE GanttData1 SET TaskId=@TaskId,TaskName=@TaskName,ParentId=@ParentId,StartDate=@StartDate,EndDate=@EndDate,Progress=@Progress,Predecessor=@Predecessor,Resource=@Resource,Duration=@Duration WHERE TaskId = '" + IDNumber + "'";
                using (SqlCommand sqlCommand = new SqlCommand(cmdString, con))
                {
                    sqlCommand.Parameters.AddWithValue("@TaskId", Task.TaskId);
                    sqlCommand.Parameters.AddWithValue("@TaskName", Task.TaskName);
                    sqlCommand.Parameters.AddWithValue("@StartDate", this.GetDate(Task.StartDate));
                    sqlCommand.Parameters.AddWithValue("@EndDate", this.GetDate(Task.EndDate));
                    sqlCommand.Parameters.AddWithValue("@Progress", Task.Progress);
                    if (Task.Duration == null)
                    {
                        sqlCommand.Parameters.AddWithValue("@Duration", Task.Duration).Value = "";
                    }
                    else
                    {
                        sqlCommand.Parameters.AddWithValue("@Duration", Task.Duration);
                    }
                    if (Task.ParentId == null)
                    {
                        sqlCommand.Parameters.AddWithValue("@ParentId", Task.ParentId).Value = "";
                    }
                    else
                    {
                        sqlCommand.Parameters.AddWithValue("@ParentId", Task.ParentId);
                    }
                    if (Task.Predecessor == null)
                    {
                        sqlCommand.Parameters.AddWithValue("@Predecessor", Task.Predecessor).Value = "";
                    }
                    else
                    {
                        sqlCommand.Parameters.AddWithValue("@Predecessor", Task.Predecessor);
                    }
                    if (Task.ResourceID != null)
                    {
                        var ResourceList = this.GetResourceValues(string.Join(",", Task.ResourceID.ToArray()));
                        sqlCommand.Parameters.AddWithValue("@Resource", string.Join(",", ResourceList.ToArray()));
                    }
                    else
                    {
                        sqlCommand.Parameters.AddWithValue("@Resource", Task.ResourceID).Value = "";
 
                    }
                    sqlCommand.ExecuteNonQuery();
 
 
                }
            }
            con.Close();
            return Json(Tasks, JsonRequestBehavior.AllowGet);
}

Delete method to delete the tasks from SQL database

        [HttpPost()]
        public ActionResult Delete(GanttData Task)        {
             //Delete Task 
            //Using Delete Query to delete Record from SQL Table
 
            // var connectionString = string.Format(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + Server.MapPath("App_Data") + @"\GanttDatabase2008.mdf;Integrated Security=True;Connect Timeout=30");
 
            string IDNumber = Task.TaskId;
            SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);//connectionString
            con.Open();
            SqlCommand cmd = new SqlCommand("delete from GanttData1 where TaskId = '" + IDNumber + "'", con);
            int result = cmd.ExecuteNonQuery();
            con.Close();
 
// Return as JSON object to the client side
            return Json(Task, JsonRequestBehavior.AllowGet);
        }

A simple sample to establish SQL connection and add, edit, delete and update the data to the SQL database through Gantt is available in the following link.

Sample

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied