Pages

Thursday, July 16, 2020

DataGrid CellFormatting

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataGrid
{
    public partial class Form1 : Form
    {
        private Panel buttonPanel = new Panel();
        private DataGridView customerDataGridView = new DataGridView();
        private Button addNewRowButton = new Button();
        private Button deleteRowButton = new Button();

        public Form1()
        {
            this.Load += new EventHandler(Form1_Load);
        }

        private void Form1_Load(System.Object sender, System.EventArgs e)
        {
            SetupLayout();
            SetupDataGridView();
            PopulateDataGridView();
        }

        private void songsDataGridView_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
        {
            if(e != null)
            {
                if (this.customerDataGridView.Columns[e.ColumnIndex].Name == "FirstName")
                {
                    if (e.Value != null)
                    {
                        // Check for the string "pink" in the cell.
                        string stringValue = (string)e.Value;
                        stringValue = stringValue.ToLower();
                        if ((stringValue.IndexOf("ram") > -1))
                        {
                            e.CellStyle.BackColor = Color.Pink;
                        }
                    }
                }
                if (this.customerDataGridView.Columns[e.ColumnIndex].Name == "DOB")
                {
                    if (e.Value != null)
                    {
                        try
                        {
                            e.Value = DateTime.Parse(e.Value.ToString()).ToLongDateString();
                            e.FormattingApplied = true;
                        }
                        catch(FormatException)
                        {
                            Console.WriteLine("{0} is not a valid date", e.Value.ToString());
                        }
                    }
                }
            }
        }

        private void addNewRowButton_Click(object sender, EventArgs e)
        {
            this.customerDataGridView.Rows.Add();
        }

        private void deleteRowButton_Click(object sender, EventArgs e)
        {
            if (this.customerDataGridView.SelectedRows.Count > 0 &&
                this.customerDataGridView.SelectedRows[0].Index !=
                this.customerDataGridView.Rows.Count - 1)
            {
                this.customerDataGridView.Rows.RemoveAt(
                    this.customerDataGridView.SelectedRows[0].Index);
            }
        }

        private void SetupLayout()
        {
            this.Size = new Size(600, 500);

            addNewRowButton.Text = "Add Row";
            addNewRowButton.Location = new Point(10, 10);
            addNewRowButton.Click += new EventHandler(addNewRowButton_Click);

            deleteRowButton.Text = "Delete Row";
            deleteRowButton.Location = new Point(100, 10);
            deleteRowButton.Click += new EventHandler(deleteRowButton_Click);

            buttonPanel.Controls.Add(addNewRowButton);
            buttonPanel.Controls.Add(deleteRowButton);
            buttonPanel.Height = 50;
            buttonPanel.Dock = DockStyle.Bottom;

            this.Controls.Add(this.buttonPanel);
        }

        private void SetupDataGridView()
        {
            this.Controls.Add(customerDataGridView);

            customerDataGridView.ColumnCount = 4;

            customerDataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Navy;
            customerDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
            customerDataGridView.ColumnHeadersDefaultCellStyle.Font =
                new Font(customerDataGridView.Font, FontStyle.Bold);

            customerDataGridView.Name = "customerDataGridView";
            customerDataGridView.Location = new Point(8, 8);
            customerDataGridView.Size = new Size(500, 250);
            customerDataGridView.AutoSizeRowsMode =
                DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
            customerDataGridView.ColumnHeadersBorderStyle =
                DataGridViewHeaderBorderStyle.Single;
            customerDataGridView.CellBorderStyle = DataGridViewCellBorderStyle.Single;
            customerDataGridView.GridColor = Color.Black;
            customerDataGridView.RowHeadersVisible = false;

            customerDataGridView.Columns[0].Name = "PersonID";
            customerDataGridView.Columns[1].Name = "FirstName";
            customerDataGridView.Columns[2].Name = "Country";
            customerDataGridView.Columns[3].Name = "DOB";
            customerDataGridView.Columns[0].DefaultCellStyle.Font =
                new Font(customerDataGridView.DefaultCellStyle.Font, FontStyle.Italic);

            customerDataGridView.SelectionMode =
                DataGridViewSelectionMode.FullRowSelect;
            customerDataGridView.MultiSelect = false;
            customerDataGridView.Dock = DockStyle.Fill;

            customerDataGridView.CellFormatting += new
                DataGridViewCellFormattingEventHandler(
                songsDataGridView_CellFormatting);
        }

        private void PopulateDataGridView()
        {

            string[] row0 = {"1","Ram","India","1/10/1970"};
            string[] row1 = {"2","Rahul","India", "2/23/1972" };
            string[] row2 = {"3","Soni","India", "3/24/1986" };
            string[] row3 = {"4","Vicky","India", "4/25/1980" };
            string[] row4 = {"5","Lynda","UK","5/26/1990"};
            string[] row5 = {"6","Kim","US","6/27/1986"};
            string[] row6 = {"7","Miller","US","7/28/1990"};

            customerDataGridView.Rows.Add(row0);
            customerDataGridView.Rows.Add(row1);
            customerDataGridView.Rows.Add(row2);
            customerDataGridView.Rows.Add(row3);
            customerDataGridView.Rows.Add(row4);
            customerDataGridView.Rows.Add(row5);
            customerDataGridView.Rows.Add(row6);

            customerDataGridView.Columns[0].DisplayIndex = 0;
            customerDataGridView.Columns[1].DisplayIndex = 1;
            customerDataGridView.Columns[2].DisplayIndex = 3;
            customerDataGridView.Columns[3].DisplayIndex = 2;
         
        }
    }
}



Thursday, January 16, 2020

angularjs-crud operation using asp net mvc

First, we create an MVC project. Go to File-> New-> Project and select “ASP.NET Web Application”.

Now, select MVC template for the project.

In Solution Explorer window, we can see the structure of our project.

Now, we add the model classes in our project. We have an Employee table which we will use in our project and implement the CRUD operation on.

CREATE TABLE [dbo].[Employee](  
[Emp_Id] [int] IDENTITY(1,1) NOT NULL,  
[Emp_Name] [varchar](max) NULL,  
[Emp_City] [varchar](max) NULL,  
[Emp_Age] [int] NULL,  
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
(  
[Emp_Id] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  
GO  




 

For database CRUD operation, we will use the Entity Framework Data First approach. For this, right click on “Model” folder and click on “New Item” option.


Now, select “ADO.NET Entity Data Model” and name it as “EmployeeModel”.

Establish a connection with “SQL Server Database” Engine.


Select Employee table Entity Data Model Wizard and click on Finish button.

Now, go to your project’s Model folder where you can see that Employee Model class has been created. So, you have successfully created a connection with database.


After this, we download and install the AngularJS package. Right click on Project Name and select “Manage NuGet Packages” option and download the AngularJS packages.


In Scripts folder, you can find that AngularJS files have been installed successfully.

Now, we create the Employee Controller. So, right click on Controller Folder and create an empty Controller.

Now, copy and paste the following code into your Employee Controller section.

  1. using AngularCRUD.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. namespace AngularCRUD.Controllers {  
  8.     public class EmployeeController: Controller {  
  9.         // GET: Employee  
  10.         public ActionResult Index() {  
  11.                 return View();  
  12.             }  
  13.             /// <summary>  
  14.             ///   
  15.             /// Get All Employee  
  16.             /// </summary>  
  17.             /// <returns></returns>  
  18.         public JsonResult Get_AllEmployee() {  
  19.                 using(DemoEntities Obj = new DemoEntities()) {  
  20.                     List < Employee > Emp = Obj.Employees.ToList();  
  21.                     return Json(Emp, JsonRequestBehavior.AllowGet);  
  22.                 }  
  23.             }  
  24.             /// <summary>  
  25.             /// Get Employee With Id  
  26.             /// </summary>  
  27.             /// <param name="Id"></param>  
  28.             /// <returns></returns>  
  29.         public JsonResult Get_EmployeeById(string Id) {  
  30.                 using(DemoEntities Obj = new DemoEntities()) {  
  31.                     int EmpId = int.Parse(Id);  
  32.                     return Json(Obj.Employees.Find(EmpId), JsonRequestBehavior.AllowGet);  
  33.                 }  
  34.             }  
  35.             /// <summary>  
  36.             /// Insert New Employee  
  37.             /// </summary>  
  38.             /// <param name="Employe"></param>  
  39.             /// <returns></returns>  
  40.         public string Insert_Employee(Employee Employe) {  
  41.                 if (Employe != null) {  
  42.                     using(DemoEntities Obj = new DemoEntities()) {  
  43.                         Obj.Employees.Add(Employe);  
  44.                         Obj.SaveChanges();  
  45.                         return "Employee Added Successfully";  
  46.                     }  
  47.                 } else {  
  48.                     return "Employee Not Inserted! Try Again";  
  49.                 }  
  50.             }  
  51.             /// <summary>  
  52.             /// Delete Employee Information  
  53.             /// </summary>  
  54.             /// <param name="Emp"></param>  
  55.             /// <returns></returns>  
  56.         public string Delete_Employee(Employee Emp) {  
  57.                 if (Emp != null) {  
  58.                     using(DemoEntities Obj = new DemoEntities()) {  
  59.                         var Emp_ = Obj.Entry(Emp);  
  60.                         if (Emp_.State == System.Data.Entity.EntityState.Detached) {  
  61.                             Obj.Employees.Attach(Emp);  
  62.                             Obj.Employees.Remove(Emp);  
  63.                         }  
  64.                         Obj.SaveChanges();  
  65.                         return "Employee Deleted Successfully";  
  66.                     }  
  67.                 } else {  
  68.                     return "Employee Not Deleted! Try Again";  
  69.                 }  
  70.             }  
  71.             /// <summary>  
  72.             /// Update Employee Information  
  73.             /// </summary>  
  74.             /// <param name="Emp"></param>  
  75.             /// <returns></returns>  
  76.         public string Update_Employee(Employee Emp) {  
  77.             if (Emp != null) {  
  78.                 using(DemoEntities Obj = new DemoEntities()) {  
  79.                     var Emp_ = Obj.Entry(Emp);  
  80.                     Employee EmpObj = Obj.Employees.Where(x => x.Emp_Id == Emp.Emp_Id).FirstOrDefault();  
  81.                     EmpObj.Emp_Age = Emp.Emp_Age;  
  82.                     EmpObj.Emp_City = Emp.Emp_City;  
  83.                     EmpObj.Emp_Name = Emp.Emp_Name;  
  84.                     Obj.SaveChanges();  
  85.                     return "Employee Updated Successfully";  
  86.                 }  
  87.             } else {  
  88.                 return "Employee Not Updated! Try Again";  
  89.             }  
  90.         }  
  91.     }  
  92. }  

After creating the Controller, now, we create a View. Right click on Index method and create an Empty View.



Paste the following code into the Index View:

  1. @{  
  2. ViewBag.Title = "Index";  
  3. }  
  4.   
  5. <style>  
  6. .btn-space {  
  7. margin-left: -5%;  
  8. background-color: cornflowerblue;  
  9. font-size: large;  
  10. }  
  11. </style>  
  12. <h2>Index</h2>  
  13. <div ng-app="myApp">  
  14.     <div ng-controller="myCtrl" ng-init="GetAllData()" class="divList">  
  15.         <p class="divHead">List of Employee</p>  
  16.         <table cellpadding="12" class="table table-bordered table-hover">  
  17.             <tr>  
  18.                 <td>  
  19.                     <b>ID</b>  
  20.                 </td>  
  21.                 <td>  
  22.                     <b>Name</b>  
  23.                 </td>  
  24.                 <td>  
  25.                     <b>City</b>  
  26.                 </td>  
  27.                 <td>  
  28.                     <b>Age</b>  
  29.                 </td>  
  30.                 <td>  
  31.                     <b>Actions</b>  
  32.                 </td>  
  33.             </tr>  
  34.             <tr ng-repeat="Emp in employees">  
  35.                 <td>  
  36. {{Emp.Emp_Id}}  
  37. </td>  
  38.                 <td>  
  39. {{Emp.Emp_Name}}  
  40. </td>  
  41.                 <td>  
  42. {{Emp.Emp_City}}  
  43. </td>  
  44.                 <td>  
  45. {{Emp.Emp_Age}}  
  46. </td>  
  47.                 <td>  
  48.                     <input type="button" class="btn btn-warning" value="Update" ng-click="UpdateEmp(Emp)" />  
  49.                     <input type="button" class="btn btn-danger" value="Delete" ng-click="DeleteEmp(Emp)" />  
  50.                 </td>  
  51.             </tr>  
  52.         </table>  
  53.         <div class="form-horizontal" role="form">  
  54.             <div class="container">  
  55.                 <div class="row">  
  56.                     <h2>  
  57.                         <span id="spn">Add New Employee</span>  
  58.                     </h2>  
  59.                 </div>  
  60.                 <div class="row">  
  61.                     <div class="col-sm-6 col-lg-4">  
  62.                         <div class="form-group">  
  63.                             <label class="col-md-4 control-label">Name:</label>  
  64.                             <div class="col-md-8">  
  65.                                 <input type="text" class="form-control" id="inputEmail" placeholder="Name" ng-model="EmpName">  
  66.                                 </div>  
  67.                             </div>  
  68.                         </div>  
  69.                         <div class="col-sm-6 col-lg-4">  
  70.                             <div class="form-group">  
  71.                                 <label class="col-md-4 control-label">City:</label>  
  72.                                 <div class="col-md-8">  
  73.                                     <input type="text" class="form-control" id="inputPassword" placeholder="City" ng-model="EmpCity">  
  74.                                     </div>  
  75.                                 </div>  
  76.                             </div>  
  77.                             <div class="col-sm-6 col-lg-4">  
  78.                                 <div class="form-group">  
  79.                                     <label class="col-md-4 control-label">Age:</label>  
  80.                                     <div class="col-md-8">  
  81.                                         <input type="text" class="form-control" id="inputLabel3" placeholder="Age" ng-model="EmpAge">  
  82.                                         </div>  
  83.                                     </div>  
  84.                                 </div>  
  85.                             </div>  
  86.                             <div class="row">  
  87.                                 <div class="col-sm-6 col-lg-4">  
  88.                                     <input type="button" id="btnSave" class="form-control btn-space" value="Submit" ng-click="InsertData()" />  
  89.                                 </div>  
  90.                             </div>  
  91.                         </div>  
  92.                     </div>  
  93.                 </div>  
  94. @Html.Hidden("EmpID_")  
  95.   
  96.             </div>  

For CRUD operations in AngularJS, we create a JavaScript file, write the code into that file, and implement this file into our Index View.

First, create a JavaScript file and copy the following code.


JavaScript code

  1. var app = angular.module("myApp", []);  
  2. app.controller("myCtrl"function($scope, $http) {  
  3.     debugger;  
  4.     $scope.InsertData = function() {  
  5.         var Action = document.getElementById("btnSave").getAttribute("value");  
  6.         if (Action == "Submit") {  
  7.             $scope.Employe = {};  
  8.             $scope.Employe.Emp_Name = $scope.EmpName;  
  9.             $scope.Employe.Emp_City = $scope.EmpCity;  
  10.             $scope.Employe.Emp_Age = $scope.EmpAge;  
  11.             $http({  
  12.                 method: "post",  
  13.                 url: "http://localhost:39209/Employee/Insert_Employee",  
  14.                 datatype: "json",  
  15.                 data: JSON.stringify($scope.Employe)  
  16.             }).then(function(response) {  
  17.                 alert(response.data);  
  18.                 $scope.GetAllData();  
  19.                 $scope.EmpName = "";  
  20.                 $scope.EmpCity = "";  
  21.                 $scope.EmpAge = "";  
  22.             })  
  23.         } else {  
  24.             $scope.Employe = {};  
  25.             $scope.Employe.Emp_Name = $scope.EmpName;  
  26.             $scope.Employe.Emp_City = $scope.EmpCity;  
  27.             $scope.Employe.Emp_Age = $scope.EmpAge;  
  28.             $scope.Employe.Emp_Id = document.getElementById("EmpID_").value;  
  29.             $http({  
  30.                 method: "post",  
  31.                 url: "http://localhost:39209/Employee/Update_Employee",  
  32.                 datatype: "json",  
  33.                 data: JSON.stringify($scope.Employe)  
  34.             }).then(function(response) {  
  35.                 alert(response.data);  
  36.                 $scope.GetAllData();  
  37.                 $scope.EmpName = "";  
  38.                 $scope.EmpCity = "";  
  39.                 $scope.EmpAge = "";  
  40.                 document.getElementById("btnSave").setAttribute("value""Submit");  
  41.                 document.getElementById("btnSave").style.backgroundColor = "cornflowerblue";  
  42.                 document.getElementById("spn").innerHTML = "Add New Employee";  
  43.             })  
  44.         }  
  45.     }  
  46.     $scope.GetAllData = function() {  
  47.         $http({  
  48.             method: "get",  
  49.             url: "http://localhost:39209/Employee/Get_AllEmployee"  
  50.         }).then(function(response) {  
  51.             $scope.employees = response.data;  
  52.         }, function() {  
  53.             alert("Error Occur");  
  54.         })  
  55.     };  
  56.     $scope.DeleteEmp = function(Emp) {  
  57.         $http({  
  58.             method: "post",  
  59.             url: "http://localhost:39209/Employee/Delete_Employee",  
  60.             datatype: "json",  
  61.             data: JSON.stringify(Emp)  
  62.         }).then(function(response) {  
  63.             alert(response.data);  
  64.             $scope.GetAllData();  
  65.         })  
  66.     };  
  67.     $scope.UpdateEmp = function(Emp) {  
  68.         document.getElementById("EmpID_").value = Emp.Emp_Id;  
  69.         $scope.EmpName = Emp.Emp_Name;  
  70.         $scope.EmpCity = Emp.Emp_City;  
  71.         $scope.EmpAge = Emp.Emp_Age;  
  72.         document.getElementById("btnSave").setAttribute("value""Update");  
  73.         document.getElementById("btnSave").style.backgroundColor = "Yellow";  
  74.         document.getElementById("spn").innerHTML = "Update Employee Information";  
  75.     }  
  76. })  

Now, provide the references of AngularJS and AngularCode file that we created into Index View.


Now, I think our project is ready to work. So, let’s run the application. Press F5 and you can see that following screen will be visible on your browser.