September 2017 ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Thursday, 21 September 2017

How to use static keyword in C# with examples

21:30:00 Posted by sridhar thota , No comments
In this article, I am going to explain the static keyword concept with examples. It covers static variable, static method, static constructor and static class. I have explained how to access static variables and static methods with in a static class.

Static Variable:

1.Static keyword can be used with variables, methods, constructor and class.
2.Static variable will be created only once and it can be shared by all objects.
3.If we declare static variable as public, then we can access that variable with classname.static_variable.
4.Static variable is created when class is loaded in to memory .
class sample 
{
public string s="hello";
public static string st="am static";
}
button click
{
sample obj=new sample();
obj.s;  //non static variable so can be accessed with object of class.
obj.st; // this is error. since static variable cannot be accessed with object of class.
sample.s; //this is error. since non static variable cannot be called with classname.variablename.
sample.st;// static variable can be accessed with classname.staticvariablename.
}

Static Method:

1.Static methods are called with classname.method name directly with out creating object.
2.When we have all static methods in a class, then we can declare that class as static class.
3.Some static methods are as follows
Ex: Console.ReadLine(); // consoleclass.methodname
      Console.Write();
      MessageBox.Show();

class static sample2
{
public static void display()
{
MessageBox.Show("Am from static method");
}
button click
{
sample2 obj=new sample2(); // error . As we cannot create object for static class.
obj.display(); // this is error. cannot be accessed with object.
sample2.display(); //works fine as called with classname.methodname
}

Static Constructor:

1.Static constructor is executed only once when the class is loading in to the memory.
2.Static constructor can access only static variables.
class sample3
{
public string s="static constructor example";
public sample3() // normal constructor
{
MesssageBox.Show("Am from normal constructor");
}
static sample3() // static constructor
{
MessageBox.Show("Am from static constructor");
}
}
button click
{
sample3 obj=new sample3();
sample3 obj1=new sample3();
}

Static Class:

1. Static class cannot be instantiated, i.e., we cannot create object for static class.
2. If we have all static methods in our class then we can declare the class as static class.
class static sample4
{
public static string s="hello";
public static string st="am static variable";
public static void display()
{
MessageBox.Show("Am from static method");
MessageBox.Show("Am static class");
}
static sample4() // static constructor
{
MessageBox.Show("Am from static constructor");
}
button click
{
sample4.s;
sample4.st;
sample4.display();
}
I hope this article helped you to understand the static keyword concept in c sharp language.Suggestions and feedback are welcome.

how to validate credit card number in jquery

10:15:00 Posted by raviteja swayampu , No comments
Hi every one welcome again today i came with very useful article How to validate credit card number in jquery. For that here i am not using neither  plugins nor references.I am doing it using pure jquery script code.Here to check whether card is a valid card or not i am using Luhn algorithm or Luhn formula.

What is Luhn Algorithm:

The Luhn algorithm or Luhn formula, also known as the "modulus 10" or "mod 10" algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in the United States, Canadian Social Insurance Numbers, Israel ID Numbers and Greek Social Security Numbers (ΑΜΚΑ). It was created by IBM scientist Hans Peter Luhn.For more information about Luhn formula visit Luhn algorithm.

Now lets check how to implement luhn test in our web application.In current application i am validating credit card in two steps
1.Checking the format of card using Regular expressions.
2.Validating card number using luhn formula.

How to check format of credit card:

For step1 i used regular expressions to check whether the credit card number is in correct format or not.For example Visa card only starts with digit '4' and contains 16 numeric digits and Master Card starts with digit '5' etc.Below are some valid credit card numbers for testing purpose.

valid credit card numbers for testing

Now come to the current application.I checked the credit card with below regular expression.
/*Regular expressions to validate credit card is in valid format
    */
    var VisaReg = /^4[0-9]{12}(?:[0-9]{3})?$/;
    var AmericanExpressReg = /^3[47][0-9]{13}$/;
    var MasterCardReg = /^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$/;



1.Check the format of card with below script using regular expression.
/*Regular expressions to validate credit card is in valid format
    */
    var VisaReg = /^4[0-9]{12}(?:[0-9]{3})?$/;
    var AmericanExpressReg = /^3[47][0-9]{13}$/;
    var MasterCardReg = /^(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}$/;

    var cardnumber = $("#cardNumber").val();
    var cardtype = $("#ddlCardType").val();
    var expirydate = $("#cardExpiry").val();
    var cardholdername = $("#cardHolderName").val();

    if (cardnumber == null || cardnumber == "") {
        $("#spncardNumber").text("Please Enter Card Number");
        $("#spncardNumber").show();
        result = false;
    }
    else if (cardnumber != null && cardnumber != "") {
        if (cardtype == "VISA") {
            if (!VisaReg.test(cardnumber)) {
                $("#spncardNumber").text("Enter Valid Visa Card Number");
                $("#spncardNumber").show();
                result = false;
            }
        }
        else if (cardtype == "AMERICAN EXPRESS") {
            if (!AmericanExpressReg.test(cardnumber)) {
                $("#spncardNumber").text("Enter Valid AE Card Number");
                $("#spncardNumber").show();
                result = false;
            }
        }
        else {
            if (!MasterCardReg.test(cardnumber)) {
                $("#spncardNumber").text("Enter Valid Master Card Number");
                $("#spncardNumber").show();
                result = false;
            }
        }       
    }
2.If you enter an invalid number with starting digit as other than 4 for VISA card(Visa card start with digit 4) and see the validation message in form like below.

Validate format of credit card

3.But these regular expressions checks card format only.They can not validate the card numbers. Luhn formula will take care of it.

How to Validate Credit Card using Luhn Algorithm:

1.Below is java script code to perform luhn formula.
/*checks whether card is valid or not using luhn algoritham
current credit cards in market are following this algoritham*/
function isCardNumberValid(cardNumber, allowSpaces) {
    if (allowSpaces) {
        cardNumber = cardNumber.replace(/ /g, '');
    }
    if (!cardNumber.match(/^\d+$/)) {
        return false;
    }
    var checksum = 0;
    for (var i = 0; i < cardNumber.length; i++) {
        var n = (cardNumber.charAt(cardNumber.length - i - 1) - '0') << (i & 1);
        checksum += n > 9 ? n - 9 : n;
    }
    return (checksum % 10) == 0 && checksum > 0;
}
2.This function accepts two parameters one is card number and another one boolean values(true or false,currently this code is work for card number with spaces).
3.Now check a random number with 16 digits.Luhn algorithm says..

Validate credit card using luhn algorithm

4.In the same ways below is csharp code to check the luhn algorithm.
Luhn alogitham server validation code.

    public static class LuhnUtility
    {
        public static bool IsCardNumberValid(string cardNumber, bool allowSpaces = false)
        {
            if (allowSpaces)
            {
                cardNumber = cardNumber.Replace(" ", "");
            }

            if (cardNumber.Any(c => !Char.IsDigit(c)))
            {
                return false;
            }

            int checksum = cardNumber
               .Select((c, i) => (c - '0') << ((cardNumber.Length - i - 1) & 1))
               .Sum(n => n > 9 ? n - 9 : n);

            return (checksum % 10) == 0 && checksum > 0;
        }
    }


Download the source code for this application from Github.
Download

Conclusion:

I hope this article may help you.Suggestions and feedbacks are always welcome.

Tuesday, 19 September 2017

How to disable past dates in date picker

05:59:00 Posted by raviteja swayampu No comments
In this example we will see how to disable the previous date selection in JQuery UI date picker. To disable the previous dates we need to set the minDate property of date picker.
If you are new to jquery date picker visit How to add date picker to textbox.
We can disable previous dates in two ways
1.By setting minDate option to 0.
2.By passing today date to minDate option in datepicker.
then it will disable all the previous dates.For example see the below picture.
3.Jquery script for this application is
<script language="javascript">
    $(document).ready(function () {
        $("#txtdate").datepicker({
            minDate: 0
        });
    });
</script>
4.Or we can also write code like this using today date.
<script language="javascript">
    $(document).ready(function () { 
        var todayDate=new Date();
        $("#txtdate").datepicker({
            minDate: todayDate
        });
    });
</script>
5.Complete source code for this application is,
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Datepicker -With Disabled past date</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    var todayDate=new Date();
    $( "#datepicker" ).datepicker({
           minDate:todayDate  //or minDate:0 also works...
    });
  } );
  </script>
</head>
<body>
 
<p>Date: <input type="text" id="datepicker"></p>
 
</body>
</html>
Date picker look like below with disabled date..

how to disable past dates in datepicker

Monday, 18 September 2017

Asynchronous fileupload using jquery in mvc5

21:38:00 Posted by raviteja swayampu , No comments
In today's article i will explain about how to Asynchronously upload file in asp.net mvc web application using jquery with progress bar.In previous articles we saw about uploading file in mvc application in different ways.

Here in current application we can upload files asynchronously to server.

asynchronous file upload using jquery in mvc5

Asynchronous fileupload using jquery

1.Create asp.net mvc web application using empty template.
2.Here in this application i used jquery ajax form plugin from here github.
3.Create a controller and name it as HomeController and add Index action method as below.
public ActionResult Index()
        {
            return View();
        }
4.Add view to index action method to display file upload screen.
@{
    ViewBag.Title = "Index";
}
<h2>Jquery Asychronous file upload</h2>
<style type="text/css">
    .progress-bar{
        max-width:400px;
    }
    .progress{
        max-width:400px;
    }
</style>
<div class="container">
    <div class="row">
        <div class="col-md-5">
            @using (Ajax.BeginForm("Index", "Home", new AjaxOptions() { HttpMethod = "POST" },
            new { enctype = "multipart/form-data" }))
            {
                @Html.AntiForgeryToken();
                <input type="file" class="form-control" name="files" id="fileupload" />
                <input type="submit" class="btn btn-success" value="File upload" />
            }
            <br />
            <div class="progress">
                <div class="progress-bar">0%</div>
            </div>
            <div id="status"></div>
        </div>
    </div>
</div>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
       $(document).ready(function(){
           var bar = $('.progress-bar');
           var percent = $('.progress-bar');
           var status = $('#status');
           
           $('form').ajaxForm({
               beforeSend: function () {
                   status.empty();
                   var percentValue = '0%';
                   bar.width(percentValue);
                   percent.html(percentValue);
               },
               uploadProgress: function (event, position, total, percentComplete) {
                   var percentValue = percentComplete + '%';
                   bar.width(percentValue);
                   percent.html(percentValue);
               },
               success: function (d) {
                   var percentValue = '100%';
                   bar.width(percentValue);
                   percent.html(percentValue);
                   $('#fileupload').val('');
                   alert(d);
               },
               complete: function (xhr) {
                   status.html(xhr.responseText);
               }
           });
       });
</script>

5.In above code i used jquery script to display progress bar based on upload status of the file like above picture.
6.Below method in controller saves the file in server.
 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(IEnumerable files)
        {
            int filecount = 0;
            string msg = "";
            try
            {
                if (files != null)
                {
                    foreach (var file in files)
                    {
                        if (file != null && file.ContentLength > 0)
                        {
                            var filename = Path.GetFileName(file.FileName);
                            var path = Path.Combine(Server.MapPath("~/Files"),filename);
                            file.SaveAs(path);
                            filecount++;
                        }
                    }
                    msg = filecount + " Files Uploaded Successfully";
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            return Json(msg, JsonRequestBehavior.AllowGet);
        }
7.We can see the saved files in solution(Files folder).

asynchronous file upload using jquery in mvc5


8.To download source code for this application from Github click below.

Download

9.Conclusion

I hope this article will help you.Feedback and suggestions are welcome

How to create pivot table in excel using asp.net mvc

06:00:00 Posted by sridhar thota , No comments
Hi friends today am going to show how to create pivot table in excel sheet using c#. I got the requirement but no clear code is found for the same in the internet. So I would like to post the article with clear c# code. Hope it will be useful for those who is looking for pivot table creation using c#.

Namespaces used in this application to work on Excel files are below.
using Excel=Microsoft.Office.Interop.Excel; //microsoft interlop ddl
using OfficeOpenXml;//eplus dll
Here Microsoft.Office.Interop.dll only available in systems which are installed with micro soft office 2013.Second dll Epplus easily available on web.

How to create pivot table in excel using asp.net mvc

In this application i am creating pivot excel table in two steps.
1.Creating Excel file and storing in server.
2.Converting excel file to pivot excel table.

Creating pivot table in Excel

Step 1:Creating Excel file.
1.Create a asp.net mvc web application using empty web template.
2.Right click on models folder and create a model class name it as TProduct.
TProduct.cs:
public class TProduct
    {
        public string Category { get; set; }
        public string Place { get; set; }
        public string Name { get; set; }
        public long Price { get; set; }
        public long NoOfUnits { get; set; }
    }
3.Create data source code to generate excel file.For that add another class file in models folder and replace it with below code.
pivotdata.cs:
public class pivotdata
    {
        public List PivotData()
        {
            List _list = new List()
            {
                new TProduct {Category="Clothing",Place="Hyderabad",Name="LEVIS",Price=3000,NoOfUnits=52 },
                new TProduct {Category="Clothing",Place="Hyderabad",Name="Buffallo",Price=10000,NoOfUnits=12 },
                new TProduct {Category="Clothing",Place="Banglore",Name="FM",Price=3200,NoOfUnits=5 },
                new TProduct {Category="Clothing",Place="Banglore",Name="PUMA",Price=6400,NoOfUnits=10 },
                new TProduct {Category="Clothing",Place="Banglore",Name="LEVIS",Price=3400,NoOfUnits=20 },
                new TProduct {Category="Clothing",Place="Banglore",Name="Buffallo",Price=34400,NoOfUnits=30 },
                new TProduct {Category="Electronics",Place="Banglore",Name="IPhone",Price=72000,NoOfUnits=1 },
                new TProduct {Category="Electronics",Place="Banglore",Name="LED TV",Price=20000,NoOfUnits=4 },
                new TProduct {Category="Electronics",Place="Banglore",Name="SAMSUNG",Price=300000,NoOfUnits=5 },
                new TProduct {Category="Electronics",Place="Banglore",Name="IPhone",Price=7200,NoOfUnits=1 },
                new TProduct {Category="Electronics",Place="Hyderabad",Name="Fridge",Price=150000,NoOfUnits=10 },
                new TProduct {Category="Electronics",Place="Hyderabad",Name="Laptops",Price=40000,NoOfUnits=15 },
                new TProduct {Category="Electronics",Place="Hyderabad",Name="Laptops",Price=30000,NoOfUnits=6 },
                new TProduct {Category="Electronics",Place="Hyderabad",Name="Laptops",Price=78347,NoOfUnits=8 },
            };
            return _list;
        }
    }
4.Add Controller by right click on controllers folder --> add --> empty controller --> name it as HomeController.cs.
5.Create two action methods to in HomeController render index view and create initial excel file.
HomeController.cs
public ActionResult Index()
        {
            List _listdata = new List();
            pivotdata dal = new pivotdata();
            _listdata = dal.PivotData();
            LoadExcelData(_listdata);
            return View();
        }
        public void LoadExcelData(List _lstproduct)
        {
            string filepath = Server.MapPath("~/Content/ProductReport.xlsx");
            System.Data.DataTable _dt = new System.Data.DataTable();
            try
            {
                if (System.IO.File.Exists(filepath))
                {
                    System.IO.File.Delete(filepath);
                }
                ExcelPackage app = new ExcelPackage();
                var sheet = app.Workbook.Worksheets.Add("ProductReport");
                sheet.Cells[1, 1].LoadFromCollection(_lstproduct, true);
                Stream stream = System.IO.File.Create(filepath);
                app.SaveAs(stream);
                stream.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }       
6.Here Index() method renders the index view and gets the data from data source(from pivotData method) and sends it to LoadExcelData() method.
7.LoadExcelData method exports data came from index method to excel file and saves it on server location(Container folder in solution).

How to create pivot table in excel using asp.net mvc

Step 2: Convert Excel file to Pivot table
1.In this step we are converting the excel to pivot table.
2.Right click solution --> add folder --> name is as Utility.Add class file in utility folder to perform perform exporting excel sheet to pivot excel table.
Export.cs:
public class Export
    {
        //this method will create pivot table in excel file
        public string OfficeDll()
        {
            //gets the excel file from path
            string filepath = System.Web.HttpContext.Current.Server.MapPath("~/Content/ProductReport.xlsx");
            int rows = 0;
            Excel.Application excelApp = new Excel.Application();
            Excel.Workbook excelWorkBook = excelApp.Workbooks.Open(filepath);
            Excel.Worksheet excelworksheet = excelWorkBook.ActiveSheet;
            Excel.Worksheet sheet2 = excelWorkBook.Sheets.Add();
            try
            {
                sheet2.Name = "Pivot Table";
                excelApp.ActiveWindow.DisplayGridlines = false;
                Excel.Range oRange = excelworksheet.UsedRange;
                Excel.PivotCache oPivotCache = excelWorkBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);  // Set the Source data range from First sheet
                Excel.PivotCaches pch = excelWorkBook.PivotCaches();
                pch.Add(Excel.XlPivotTableSourceType.xlDatabase, oRange).CreatePivotTable(sheet2.Cells[3, 3], "PivTbl_2", Type.Missing, Type.Missing);// Create Pivot table
                Excel.PivotTable pvt = sheet2.PivotTables("PivTbl_2");
                pvt.ShowDrillIndicators = true;
                pvt.InGridDropZones = false;
                Excel.PivotField fld = ((Excel.PivotField)pvt.PivotFields("CATEGORY"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld = ((Excel.PivotField)pvt.PivotFields("PLACE"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld = ((Excel.PivotField)pvt.PivotFields("NAME"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld = ((Excel.PivotField)pvt.PivotFields("PRICE"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlRowField;
                fld.set_Subtotals(1, false);

                fld = ((Excel.PivotField)pvt.PivotFields("NoOfUnits"));
                fld.Orientation = Excel.XlPivotFieldOrientation.xlDataField;

                sheet2.UsedRange.Columns.AutoFit();
                pvt.ColumnGrand = true;
                pvt.RowGrand = true;
                excelApp.DisplayAlerts = false;
                excelworksheet.Delete();
                sheet2.Activate();
                sheet2.get_Range("B1", "B1").Select();
                excelWorkBook.SaveAs(filepath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                excelApp.DisplayAlerts = false;
                excelWorkBook.Close(0);
                excelApp.Quit();
                Marshal.ReleaseComObject(excelWorkBook);
                Marshal.ReleaseComObject(excelApp);
            }
            catch (Exception ex)
            {
                excelWorkBook.Close(0);
                excelApp.Quit();
                Marshal.ReleaseComObject(excelWorkBook);
                Marshal.ReleaseComObject(excelApp);

                return ex.Message;
            }
            return filepath;
        }
    }    
3.The above method OfficeDll converts excel sheet to pivot table in excel.
4.I added another action method in HomeController of type FileResult to return the Pivot excel file as output in browser when we click on button.
 //Returns the pivot excel table      
        public FileResult Export()
        {
            string finalpath = "";
            Export obj = new Utility.Export();
            finalpath= obj.OfficeDll();
            return File(finalpath, "application/vnd.ms-excel");
        }
5.Add view to index action.
index.cshtml page:

How to create pivot table in excel using asp.net mvc

Download the source code for this application from Github.

Conclusion:

I hope this article help you.Feedback and suggestions are welcome.

Sunday, 17 September 2017

How to compare dates using javascript

05:17:00 Posted by raviteja swayampu No comments
Comparing dates is a common task to do as a front end developer is to process Date objects, and frequently that means to compare them.Today we will learn how to compare dates in java script.There are many predefined methods for comparing dates but in this article i am only showing the simplest ways to compare dates in java script.

Setting a Date Object:

1.Date is the predefined class in java script.To perform any operations on dates we have to create object for Date class.
2.There are 4 ways to instantiate date object like below.
new Date() //This will return current date and time.
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
3.The date constructor accepts parameters like above.Lets see some examples of creating date objects and output in browser console.

how to compare dates in javascript

Comparing Dates:

Comparing two dates.Let take two dates and i am comparing both with below java script function CompareDate() below.
     function CompareDate() {
       //Note: 00 is month i.e. January
       var dateOne = new Date(2010, 00, 15); //Year, Month, Date
       var dateTwo = new Date(2011, 00, 15); //Year, Month, Date
       if (dateOne > dateTwo) {
            alert("Date One is greather then Date Two.");
        }else {
            alert("Date Two is greather then Date One.");
        }
    }
    CompareDate();
4.Lets see the output for this function in browser console.

how to compare dates in javascript



5.Similarly compare two dates with time.Now instantiate date objects by passing time values along with date parameters in date constructor.
   function CompareDate() {
       //            new Date(Year, Month, Date, Hr, Min, Sec);
       var dateOne = new Date(2012, 04, 20, 14, 55, 59);
       var dateTwo = new Date(2012, 04, 20, 12, 10, 20);
        //Note: 04 is month i.e. May
       if (dateOne > dateTwo) {
            alert("Date One is greather then Date Two.");
        }else {
            alert("Date Two is greather then Date One.");
        }
       if(dateOne==dateTwo){
           alert("Both dates are equal");
       }else{
           alert("Dates are not equal");
       }
    }
    CompareDate();
The below some useful predefined methods to performs operations on dates in java script.
getDate: Returns the day of the month (1-31) for the specified date according to local time.
getDay: Returns the day of the week (0-6) for the specified date according to local time.
getFullYear: Returns the year (4 digits for 4-digit years) of the specified date according to local time.
getHours: Returns the hour (0-23) in the specified date according to local time.
getMilliseconds: Returns the milliseconds (0-999) in the specified date according to local time.
getMinutes: Returns the minutes (0-59) in the specified date according to local time.
getMonth: Returns the month (0-11) in the specified date according to local time.
getSeconds: Returns the seconds (0-59) in the specified date according to local time.
getTime: Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC (negative for prior times).
getTimezoneOffset: Returns the time-zone offset in minutes for the current locale.
getUTCDate: Returns the day (date) of the month (1-31) in the specified date according to universal time.
getUTCDay: Returns the day of the week (0-6) in the specified date according to universal time.
getUTCFullYear: Returns the year (4 digits for 4-digit years) in the specified date according to universal time.
getUTCHours: Returns the hours (0-23) in the specified date according to universal time.
getUTCMilliseconds: Returns the milliseconds (0-999) in the specified date according to universal time.
getUTCMinutes: Returns the minutes (0-59) in the specified date according to universal time.
getUTCMonth: Returns the month (0-11) in the specified date according to universal time.
getUTCSeconds: Returns the seconds (0-59) in the specified date according to universal time.
getYear: Returns the year (usually 2-3 digits) in the specified date according to local time. Use getFullYear instead.
setDate: Sets the day of the month (1-31) for a specified date according to local time.
setFullYear: Sets the full year (4 digits for 4-digit years) for a specified date according to local time.
setHours: Sets the hours (0-23) for a specified date according to local time.
setMilliseconds: Sets the milliseconds (0-999) for a specified date according to local time.
setMinutes: Sets the minutes (0-59) for a specified date according to local time.
setMonth: Sets the month (0-11) for a specified date according to local time.
setSeconds: Sets the seconds (0-59) for a specified date according to local time.
setTime: Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC, allowing for negative numbers for times prior.
setUTCDate: Sets the day of the month (1-31) for a specified date according to universal time.
setUTCFullYear: Sets the full year (4 digits for 4-digit years) for a specified date according to universal time.
setUTCHours: Sets the hour (0-23) for a specified date according to universal time.
setUTCMilliseconds: Sets the milliseconds (0-999) for a specified date according to universal time.
setUTCMinutes: Sets the minutes (0-59) for a specified date according to universal time.
setUTCMonth: Sets the month (0-11) for a specified date according to universal time.
setUTCSeconds: Sets the seconds (0-59) for a specified date according to universal time.
setYear: Sets the year (usually 2-3 digits) for a specified date according to local time. Use setFullYear instead.
toDateString: Returns the "date" portion of the Date as a human-readable string.

I hope this article helped you.Feedback and suggestions are welcome.

Thursday, 14 September 2017

Jqgrid server side sorting and paging

20:29:00 Posted by raviteja swayampu No comments
In this article we will learn about how to implement server side paging and sorting in jqgrid in asp.net mvc web application.If you are new to jqgrid please refer following articles on jqgrid in this blog.


Now lets see how to implement server side sorting and paging in jqgrid,
To implement sorting and paging on server side first we must set jqgrid property loadonce:false.Now jqgrid depends on server side method to implement paging and sorting otherwise server side sorting and paging will not be performed.
Note: download source code for jqgrid in this blog before going to implement present application.Here in this application i am using previous jqgrid application code.
1.Change the controller code with below csharp code.
public JsonResult GetValues(string sidx, string sord, int page, int rows) 
        {
            DatabaseEntities1 db = new DatabaseEntities1();
            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            var Results = db.Users.Select(
                    a => new
                    {
                        a.Id,
                        a.Name,
                        a.Phone,
                        a.Address,
                        a.DOB,
                    }).ToList();
            int totalRecords = Results.Count();
            var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
            //sorting the result based on sort index column in jqgrid 
            try
            {
                switch (sidx)
                {
                    case "Name":
                        if (sord.ToUpper() == "ASC")
                            Results = Results.OrderBy(x => x.Name).ToList();
                        else
                            Results = Results.OrderByDescending(x => x.Name).ToList();
                        break;
                    case "Phone":
                        if (sord.ToUpper() == "ASC")
                            Results = Results.OrderBy(x => x.Phone).ToList();
                        else
                            Results = Results.OrderByDescending(x => x.Phone).ToList();
                        break;
                    case "Address":
                        if (sord.ToUpper() == "ASC")
                            Results = Results.OrderBy(x => x.Address).ToList();
                        else
                            Results = Results.OrderByDescending(x => x.Address).ToList();
                        break;
                    case "DOB":
                        if (sord.ToUpper() == "ASC")
                            Results = Results.OrderBy(x => x.DOB).ToList();
                        else
                            Results = Results.OrderByDescending(x => x.DOB).ToList();
                        break;
                    default:
                        Results = Results.OrderByDescending(s => s.Id).ToList();
                        break;
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            //server side paging for grid               
            Results = Results.Skip(pageIndex * pageSize).Take(pageSize).ToList();
            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,
                rows = Results
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }
2.Below is the jquery script for jqgrid.


$(function () {
    debugger;
    $("#grid").jqGrid({
        url: "/Jqgrid/GetValues",
        datatype: 'json',
        mtype: 'Get',
        //table header name 
        colNames: ['Id', 'Name', 'Phone', 'Address', 'DOB'],
        //colModel takes the data from controller and binds to grid 
        colModel: [
            { key: true, hidden: false, name: 'Id',align:'center',index: 'Id', editable: false,width:50 },
            { key: false, name: 'Name', index: 'Name',align:'center',editable: true,sortable:true },
            { key: false, name: 'Phone', index: 'Phone',align:'center',editable: true,sortable: true },
            { key: false, name: 'Address', index: 'Address',align:'center',editable: true,sortable: true },
            { key: false, name: 'DOB', index: 'DOB', editable: true,align:'center',sortable:true,formatter: 'date', formatoptions: { newformat: 'd/m/Y' } }],
            
        pager: jQuery('#pager'),
        rowNum: 10,
        rowList: [10, 20, 30, 40],
        height: '100%',
        width: 600,
        //loadonce:true,
        sortname: 'Id',
        sortorder:'desc',
        viewrecords: true,
        caption: 'Server side sorting & paging in Jqgrid',
        emptyrecords: 'No records to display',
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false,
            Id: "0"
        },
        multiselect: false,
        //loadComplete: function () {
        //    var $this = $(this);
        //    if ($this.jqGrid("getGridParam", "datatype") !== "local") {
        //        setTimeout(function () {
        //            $this.jqGrid("setGridParam", { rowNum: 10 }); // the real value
        //            $this.trigger("reloadGrid");
        //        }, 50);
        //    }
        //},
        //pager-you have to choose here what icons should appear at the bottom
        //like edit,create,delete icons
    }).navGrid('#pager', { edit: true, add: true, del: true, search: false, refresh: true },
        {
            // edit options
            zIndex: 100,
            url: '/Jqgrid/Edit',
            closeOnEscape: true,
            closeAfterEdit: true,
            recreateForm: true,
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        },
        {
            // add options
            zIndex: 100,
            url: "/Jqgrid/Create",
            closeOnEscape: true,
            closeAfterAdd: true,
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        },
        {
            // delete options
            zIndex: 100,
            url: "/Jqgrid/Delete",
            closeOnEscape: true,
            closeAfterDelete: true,
            recreateForm: true,
            msg: "Are you sure you want to delete this task?",
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        });
});

jqgrid server side sorting and paging

3.I hope this article may help you.All feed backs and suggestions are welcome.

Wednesday, 13 September 2017

How to create and consume web service in mvc

20:09:00 Posted by sridhar thota , No comments
Web Service still plays a very important role in today's applications in order to share information on multiple applications.In this tutorial i am going to explain how to create and consume basic web service in asp.net mvc web application.There might be some other articles too, but I explained clearly step by step which will be use full for beginners to understand easily.


What is a webservice

Webservice is a class managed by the webserver, which is accessible to client application based on
following standards.

1.Web Service Description Language(WSDL):
Web service description language is a xml based language for providing complete description of webservice to client application.Description contains which data types used, method names and address in webservice.

2.SOAP(Simple Object Access Protocol):
Simple object access protocol is the formatting protocol which provides standards for sending request and receiving response between client and web service.

3.HTTP(Hyper Text Transfer Protocol):
Hyper text transfer protocol is used as a transport to carry request in form of soap message from client to web server and response from web server to client.

4.UDDI(Universal Description Discovery Intergration):
Universal description discovery and integration is used for describing the services and is platform independent.

Mechanism of SOAP,HTTP and Web Service:
1.Client application method call will go to proxy,proxy will convert method call to xml format that
is soap message.
2.Soap message will reach web server via HTTP protocol.
3.Webserver will create object of webservice and method is executed.
4.The result in the form of soap format is given to client back over HTTP.

Create and consume web service

In current article we will learn about how to create web service has a web method to share employee data and how to consume that service with client application.
1.Create a asp.net mvc empty web application.Right click on website solution --> add --> new item --> select web service from list(.asmx file) --> name it as EmployeeService.asmx.
2.Create a model class in Models folder.
Employee.cs
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Designation { get; set; }
        public long Salary { get; set; }
        public string City { get; set; } 
    }
3.Now replace EmployeeService.asmx file with below code.(Here i am using static data in controller instead of going to database).


using System;
using System.Collections.Generic;
using System.Web.Services;
using SampleService.Models;

namespace SampleService
{
    /// 
    /// Summary description for EmployeeService
    /// 
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class EmployeeService : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        [WebMethod]
        public List EmployeeData()
        {
            //data source
            List _list = new List()
            {
                new Employee { Id=1,Name="Raviteja Swayampu",Designation="Developer",Salary=20000,City="Hyderabad"},
                new Employee { Id=2,Name="Bill Gates",Designation="CEO",Salary=1000000,City="USA"},
                new Employee { Id=3,Name="Warren Buffet",Designation="Chairman",Salary=23939345,City="USA"},
                new Employee { Id=4,Name="Mark",Designation="Designer",Salary=324834,City="Jermany"},
                new Employee { Id=5,Name="Frank",Designation="QA Analyst",Salary=83439,City="France"}
            };
            return _list;
        }
    }
}
Note: The methods present in web service which are to be exposed to client application are attributed with web method.Example,
[webmethod]
Public void mymethod()
{
//some logic.
}
4.In above service i created EmployeeData() web method to share employee data as a service and Helloworld method to display a string.
5.If you run the service we will see the two methods in browser like below.

how to create and consume basic web service



6.Below is the Employee data from service in xml format.

how to create and consume basic web service

Create a client to consume web service

1.Now right click on controllers folder --> add controller and name it as HomeController.
2.Here i created two methods Index action method to render index page where we are displaying grid table to display with data coming from service.Second method DisplayTableData() sends json data to view to bind data to grid table.
HomeController.cs
public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult DisplayTableData()
        {
            SampleService.EmployeeService objservice = new SampleService.EmployeeService();
            var datafromservice = objservice.EmployeeData().ToList();
            return Json(datafromservice, JsonRequestBehavior.AllowGet);
        }
    }
3.Add view to index action method and replace view code with below html code.
@{
    ViewBag.Title = "www.mitechdev.com";
}

<h3 class="text-info">Creating and consuming basic web service</h3>
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <table id="tblEmployee" class="table table-responsive table-bordered">
                <tr>
                    <td><strong>Id</strong></td>
                    <td><strong>Employee Name</strong></td>
                    <td><strong>Designation</strong></td>
                    <td><strong>Salary</strong></td>
                    <td><strong>City</strong></td>
                </tr>
                <tbody>                    
                </tbody>
            </table>
        </div>
    </div>
</div>


4.Now the design of the page completed it is time to bind table with data using jquery ajax method.
$(document).ready(function () {
        var url = '@Url.Action("DisplayTableData","Home")';
        $.get(url, null, function (data) {
            var result = "";
            $.each(data, function (index, item) {
                result = "";
                result = result + "" + item.Id + "

"
                        + "" + item.Name + "

"
                        + "" + item.Designation + "

"
                        + "" + item.Salary + "

"
                        + "" + item.City + "

";
                result = result + "";
                $("#tblEmployee").append(result);
            });
        });
    });
5.In above code i am getting data from server using jquery ajax method and binding it dynamically to table using jquery script.
6.The output of this application will be shown in browser like below.

how to create and consume basic web service



Note: run the service application first before running of client application other wise you will get a exception like "Web Exception was unhandled by user code,unable to connect to remote server".
So,make sure that server is running before you run client application.
Download source code for this application from Github.

Conclusion

Thanks for reading the article.I hope it is use full for beginners to understand how to create and consume a web service in asp.net. Feed backs and suggestions are welcome.

Tuesday, 12 September 2017

How to insert form data in multiple table using jquery

11:32:00 Posted by raviteja swayampu , No comments
In this article we gonna learn about how to insert from data in multiple tables using jquery ajax in asp.net web application.In real time applications it is not a good practice to save all customer data in one table.They save data in multiple tables and link them using relations(using foreign keys).In current article we will see how to do it.Before going to article check related articles in series of asp.net mvc application development.


Inserting form data in multiple table

Topics covered in this article,
1.Creating database for saving form data in multiple forms.
2.Preparing model classes(Data transfer objects).
3.Server side code to save form values into database tables.

4.How to work with multiple ajax(post) calls in jquery to send data from html page to controller.
Here,to interactive with database i used entity framework ORM tool to perform data base operations.Now let's come to current article,

Steps:

1.Create a asp.net web application in visual studio using empty mvc template.
2.Create data base for this applications using below sql script code.
CREATE TABLE [dbo].[TUser] (
    [Id]          INT           IDENTITY (1, 1) NOT NULL,
    [Name]        NVARCHAR (50) NOT NULL,
    [Email]       NVARCHAR (50) NOT NULL,
    [PhoneNumber] BIGINT        NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[TOrders] (
    [OrderId]     INT           IDENTITY (1, 1) NOT NULL,
    [ItemName]    NVARCHAR (50) NOT NULL,
    [PaymentType] NVARCHAR (50) NOT NULL,
    [Price]       BIGINT        NOT NULL,
    [Userid]      BIGINT        NOT NULL,
    PRIMARY KEY CLUSTERED ([OrderId] ASC)
);
CREATE TABLE [dbo].[TAddress] (
    [AddressId] BIGINT        IDENTITY (1, 1) NOT NULL,
    [Colony]    NVARCHAR (50) NOT NULL,
    [State]     NVARCHAR (50) NOT NULL,
    [Country]   NVARCHAR (50) NOT NULL,
    [Userid]    BIGINT        NOT NULL,
    PRIMARY KEY CLUSTERED ([AddressId] ASC)
);
3.Here i created 3 tables TUser,TAddress and TOrders where i am maintaining relationship between three tables using userid.
4.I created a procedure to save user data and prints the latest saved identity column(userid) of TUser table and saving it as a foreign key in TAddress and TOrders tables.
CREATE PROCEDURE [dbo].[sp_InsertUser]
 @Name nvarchar(225) = null,
 @Email nvarchar(225) = null,
 @PhoneNumber Bigint=0
AS
BEGIN
 INSERT INTO TUser(Name,Email,PhoneNumber) VALUES(@Name,@Email,@PhoneNumber)
 DECLARE @Id INT
 SET @[email protected]@IDENTITY
 SELECT @Id AS id
END
5.(Add ADO.NET Entity data model)Right click on Models folder --> Add --> ADO.NET Entity DataModel --> Name it --> Select EF designer from Database from Entity Data Model Wizard --> Select connection string and web.config --> click next --> Choose your database objects and settings(here tables and stored procedure you created) and give name to model namespace--> click finish.

6.Add a controller with index action method and add view to index action method and replace index view code with below html code.
@{
    ViewBag.Title = "www.mitechdev.com";
}

<link href="~/Content/Site.css" rel="stylesheet" />
<div class="container">
    <form id="contact" action="" method="post">
        <h4 class="text-info"><strong>Saving Form data in Multiple Tables in DB</strong></h4>
        <fieldset>
            <input placeholder="Your name" id="txtname" type="text" tabindex="1" required autofocus>
        </fieldset>
        <fieldset>
            <input placeholder="Your Email Address" id="txtemail" type="email" tabindex="2" required>
        </fieldset>
        <fieldset>
            <input placeholder="Your Phone Number" id="txtphone" type="tel" tabindex="3" required>
        </fieldset>
        <fieldset>
            <input placeholder="Colony" id="txtcolony" type="text" tabindex="4" required />
        </fieldset>
        <fieldset>
            <input placeholder="State" id="txtstate" type="text" tabindex="4" required />
        </fieldset>
        <fieldset>
            <select id="ddlcountry" required>
                <option value="">-select country-</option>
                <option value="India">India</option>
                <option value="USA">USA</option>
                <option value="United Kingdom">United Kingdom</option>
                <option value="Canada">Canada</option>
                <option value="Jermany">Jermany</option>
            </select>
        </fieldset>
        <fieldset>
            <input placeholder="ItemName" id="txtitemname" type="text" tabindex="4" required />
        </fieldset>
        <fieldset>
            <select id="ddlpaymentttype">
                <option value="">-select-</option>
                <option value="Credit Card">Credit Card</option>
                <option value="Debit Card">Debit Card</option>
                <option value="Net Banking">Net Banking</option>
                <option value="Other">Other</option>
            </select>
        </fieldset>
        <fieldset>
            <input placeholder="Price" id="txtprice" type="text" tabindex="4" required />
        </fieldset>
        <fieldset>
            <button name="submit" type="button" id="contact-submit">Submit</button>
        </fieldset>
        <p class="copyright">Designed by <a href="https://mitechdev.com" target="_blank" title="mitechdev.com">Mitechdev.com</a></p>
    </form>
</div>
7.The form screen look like below with attractive css styles.

how to insert form data in multiple table mitechdev.com
8.Add below script to send data from form to server using ajax.Here,in above form i want to save first 3 fields in TUser table,next 3 fields in TAddress table and final 3 fields in TOrders table.
9.First i am inserting data in TUser using ajax post method next in TAddress using another post ajax method and TOrders using another ajax method.
$(document).ready(function () {
        $("#contact-submit").click(function () {
            var url = "@Url.Action("SaveUser","Home")";
            debugger;
            var userdata = {
                Name: $.trim($("#txtname").val()),
                Email: $.trim($("#txtemail").val()),
                PhoneNumber:$.trim($("#txtphone").val())
            };
            $.post(url, { UserData: userdata }, function (data) {
                debugger;
                if (data!=0 && data > 0) {
                    var url = "@Url.Action("SaveAddress","Home")";
                    var addressdata = {
                        Colony: $.trim($("#txtcolony").val()),
                        State: $.trim($("#txtstate").val()),
                        Country: $.trim($("#ddlcountry").val()),
                        Userid:data
                    };
                    $.post(url, { AddressData: addressdata }, function (response) {
                        debugger;
                        if (response == true) {
                            var orderdata = {
                                ItemName: $.trim($("#txtitemname").val()),
                                PaymentType: $.trim($("#ddlpaymentttype").val()),
                                Price: $.trim($("#txtprice").val()),
                                Userid:response
                            };
                            $.post("@Url.Action("SaveOrders", "Home")", { OrdersData: orderdata }, function (result) {
                                debugger;
                                if (result == true) {
                                    alert("Form data saved successfully in 3 tables");
                                    resetForm();
                                }
                            });
                        }
                    });
                }
            });
        });
    });
    function resetForm() {
        $("#txtname").val("");
        $("#txtemail").val("");
        $("#txtphone").val("");
        $("#txtcolony").val("");
        $("#txtstate").val("");
        $("#ddlcountry").val("");
        $("#txtitemname").val("");
        $("#ddlpaymentttype").val("");
        $("#txtprice").val("");
    }
Note: For this application i not performing any client validations.Refer this link to know how to perform jquery validations on form.In above code resetForm() function clears all user input data after saving in database.
10.Now replace the controller code with below code.


public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult SaveUser(TUser UserData)
        {
            int Userid = 0;
            try
            {
                if (UserData != null)
                {
                    using (DatabaseEntities db = new DatabaseEntities())
                    {
                        //saves the user data and returns userid from procedure.
                        var id = db.Database.SqlQuery("sp_InsertUser @Name,@Email,@PhoneNumber",
                            new SqlParameter("Name",UserData.Name),
                            new SqlParameter("Email",UserData.Email),
                            new SqlParameter("PhoneNumber",UserData.PhoneNumber)).Single();
                        Userid = id;
                    }
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            return Json(Userid, JsonRequestBehavior.AllowGet);
        }
        //saves Address data TAddress table
        public JsonResult SaveAddress(TAddress AddressData)
        {        
            bool result = false;
            try
            {
                if (AddressData != null)
                {
                    using (DatabaseEntities db = new DatabaseEntities())
                    {
                        db.TAddresses.Add(AddressData);
                        db.SaveChanges();
                        result = true;
                    }
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        //saves orderdata in TOrders table
        public JsonResult SaveOrders(TOrder OrdersData)
        {
            bool result = false;
            try
            {
                if (OrdersData != null)
                {
                    using (DatabaseEntities db = new DatabaseEntities())
                    {
                        db.TOrders.Add(OrdersData);
                        db.SaveChanges();
                        result = true;
                    }
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
11.After saving all form data into 3 tables in database a response message comes like below.

how to insert form data in multiple table mitechdev.com
12.Download source code for this application from Github.

Conclusion:

I hope this article will help you .To get more updates please subscribe to this blog subscribe.

Sunday, 10 September 2017

crud operations in gridview using entity framework

20:34:00 Posted by raviteja swayampu , , No comments
Hi every one again.As a Dot net developer i have been writing articles on real time application on this blog.Many of my readers asked me(through comments and email) to write about asp.net web development also.So, i decided to write asp.net articles along with real time applications also.The current article is step by step procedure to implement basic crud operations on grid view in asp.net with entity framework as data base framework.


Other related articles on crud operations in this blog is as follows,
Now come to current article.In this article we gonna learn about basic crud operations on grid view(create,retrive,update and delete operations) along with cascading drop down list in create and update forms.

crud operations in gridview using entity framework

Topics covered in this article
1.Creating database for crud operations and cascading dropdownlist
2.Binding gridview with database data using entity framework
3.performing create,delete,update and retrive operations on grid.
4.Styling grid with responsive twitter bootstrap.

Steps to implement crud operations on gridview

1.Create asp.net web application with empty webforms template.
2.Create following tables in database to perform crud operations and implementing cascading drop down list functionality in grid.
CREATE TABLE [dbo].[Contacts] (
    [ContactID]     INT           IDENTITY (1, 1) NOT NULL,
    [ContactPerson] VARCHAR (100) NOT NULL,
    [ContactNo]     VARCHAR (20)  NOT NULL,
    [CountryID]     INT           NOT NULL,
    [StateID]       INT           NOT NULL,
    PRIMARY KEY CLUSTERED ([ContactID] ASC)
);

CREATE TABLE [dbo].[Country] (
    [CountryID]   INT           IDENTITY (1, 1) NOT NULL,
    [CountryName] VARCHAR (100) NOT NULL,
    PRIMARY KEY CLUSTERED ([CountryID] ASC)
);

CREATE TABLE [dbo].[State] (
    [StateID]   INT           IDENTITY (1, 1) NOT NULL,
    [CountryID] INT           NOT NULL,
    [StateName] VARCHAR (100) NOT NULL,
    PRIMARY KEY CLUSTERED ([StateID] ASC)
);

SET IDENTITY_INSERT [dbo].[Country] ON
INSERT INTO [dbo].[Country] ([CountryID], [CountryName]) VALUES (1, N'Brazil')
INSERT INTO [dbo].[Country] ([CountryID], [CountryName]) VALUES (2, N'China')
INSERT INTO [dbo].[Country] ([CountryID], [CountryName]) VALUES (3, N'France')
INSERT INTO [dbo].[Country] ([CountryID], [CountryName]) VALUES (4, N'India')
INSERT INTO [dbo].[Country] ([CountryID], [CountryName]) VALUES (5, N'USA')
SET IDENTITY_INSERT [dbo].[Country] OFF

SET IDENTITY_INSERT [dbo].[Contacts] ON
INSERT INTO [dbo].[Contacts] ([ContactID], [ContactPerson], [ContactNo], [CountryID], [StateID]) VALUES (1, N'Ravi teja', N'90545647865', 1, 49)
INSERT INTO [dbo].[Contacts] ([ContactID], [ContactPerson], [ContactNo], [CountryID], [StateID]) VALUES (2, N'Gopal', N'89767856457', 1, 163)
INSERT INTO [dbo].[Contacts] ([ContactID], [ContactPerson], [ContactNo], [CountryID], [StateID]) VALUES (3, N'Sridhar', N'09435898445', 1, 148)
SET IDENTITY_INSERT [dbo].[Contacts] OFF

SET IDENTITY_INSERT [dbo].[State] ON
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (1, 5, N'California')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (2, 2, N'Beijing')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (3, 5, N'Iowa')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (4, 5, N'New York')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (5, 2, N'Hebei')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (6, 2, N'Jiangsu')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (7, 5, N'New Jersey')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (8, 5, N'Massachusetts')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (9, 5, N'Connecticut')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (10, 2, N'Guangdong')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (11, 5, N'Florida')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (12, 5, N'Texas')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (13, 5, N'Armed Forces US')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (14, 5, N'Tennessee')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (15, 5, N'Kentucky')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (16, 3, N'Ile-de-3nce')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (17, 5, N'Georgia')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (18, 1, N'Rio de Janeiro')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (19, 5, N'Illinois')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (20, 1, N'Ceara')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (21, 5, N'Colorado')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (22, 2, N'Zhejiang')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (23, 5, N'Utah')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (24, 2, N'Liaoning')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (25, 4, N'Haryana')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (26, 5, N'Maryland')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (27, 2, N'Shanghai')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (28, 2, N'Tianjin')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (29, 5, N'South Carolina')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (30, 5, N'Montana')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (31, 5, N'Louisiana')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (32, 2, N'Fujian')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (33, 1, N'Santa Catarina')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (34, 1, N'Espirito Santo')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (35, 5, N'Washington')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (36, 4, N'Andhra Pradesh')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (37, 5, N'Pennsylvania')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (38, 2, N'Guangxi')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (39, 5, N'North Carolina')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (40, 2, N'Shandong')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (41, 2, N'Chongqing')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (42, 5, N'Michigan')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (43, 2, N'Hubei')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (44, 4, N'Delhi')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (45, 5, N'Arkansas')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (46, 5, N'Wisconsin')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (47, 3, N'Midi-Pyrenees')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (48, 3, N'Picardie')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (49, 1, N'Bahia')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (50, 2, N'Heilongjiang')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (51, 4, N'Tamil Nadu')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (52, 5, N'Ohio')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (53, 5, N'New Mexico')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (54, 5, N'Kansas')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (55, 5, N'Oregon')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (56, 4, N'Uttar Pradesh')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (57, 5, N'Ne1ska')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (58, 5, N'West Virginia')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (59, 5, N'Virginia')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (60, 5, N'Missouri')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (61, 5, N'Mississippi')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (62, 5, N'Rhode Island')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (63, 1, N'Sao Paulo')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (64, 2, N'Shanxi')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (65, 4, N'Karnataka')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (66, 2, N'Hunan')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (67, 5, N'4iana')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (68, 5, N'Oklahoma')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (69, 5, N'Minnesota')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (70, 5, N'Alabama')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (71, 2, N'Hainan')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (72, 5, N'Arizona')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (73, 2, N'Sichuan')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (74, 5, N'South Dakota')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (75, 4, N'Maharashtra')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (76, 5, N'Nevada')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (77, 2, N'Henan')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (78, 4, N'Kerala')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (79, 5, N'New Hampshire')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (80, 5, N'Maine')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (81, 5, N'Hawaii')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (82, 4, N'Chhattisgarh')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (83, 2, N'Anhui')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (84, 5, N'District of Columbia')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (85, 5, N'Delaware')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (86, 4, N'West Bengal')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (87, 2, N'Shaanxi')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (88, 4, N'Madhya Pradesh')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (89, 4, N'Gujarat')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (90, 3, N'3nche-Comte')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (91, 5, N'Idaho')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (92, 4, N'Rajasthan')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (93, 2, N'Nei Mongol')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (94, 3, N'Alsace')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (95, 4, N'Orissa')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (96, 2, N'Jilin')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (97, 4, N'Jharkhand')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (98, 4, N'Chandigarh')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (99, 4, N'Punjab')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (100, 3, N'Languedoc-Roussillon')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (101, 4, N'Assam')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (102, 3, N'Centre')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (103, 3, N'Champagne-Ardenne')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (104, 3, N'Bretagne')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (105, 3, N'Rhone-Alpes')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (106, 3, N'Nord-Pas-de-Calais')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (107, 3, N'Lorraine')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (108, 1, N'Rio Grande do Sul')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (109, 3, N'Provence-Alpes-Cote d''Azur')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (110, 1, N'Minas Gerais')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (111, 3, N'Limousin')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (112, 2, N'Guizhou')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (113, 3, N'Haute-Normandie')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (114, 3, N'Poitou-Charentes')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (115, 5, N'Wyoming')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (116, 4, N'Daman and Diu')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (117, 1, N'Para')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (118, 3, N'Basse-Normandie')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (119, 4, N'Bihar')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (120, 3, N'Aquitaine')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (121, 1, N'Parana')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (122, 3, N'Auvergne')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (123, 1, N'Pernambuco')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (124, 3, N'Pays de la Loire')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (125, 1, N'Amazonas')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (126, 1, N'Distrito Federal')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (127, 5, N'North Dakota')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (128, 3, N'Bourgogne')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (129, 5, N'Vermont')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (130, 1, N'Goias')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (131, 4, N'Himachal Pradesh')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (132, 1, N'Sergipe')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (133, 5, N'Alaska')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (134, 1, N'Mato Grosso do Sul')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (135, 2, N'Yunnan')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (136, 4, N'Uttarakhand')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (137, 4, N'Meghalaya')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (138, 2, N'Jiangxi')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (139, 1, N'Rio Grande do Norte')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (140, 1, N'Paraiba')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (141, 1, N'Piaui')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (142, 2, N'Gansu')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (143, 4, N'Jammu and Kashmir')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (144, 4, N'Goa')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (145, 1, N'Maranhao')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (146, 1, N'Mato Grosso')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (147, 3, N'Corse')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (148, 1, N'Alagoas')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (149, 4, N'Puducherry')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (150, 4, N'Manipur')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (151, 1, N'Tocantins')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (152, 1, N'Roraima')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (153, 1, N'Rondonia')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (154, 2, N'Xizang')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (155, 2, N'Ningxia')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (156, 2, N'Xinjiang')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (157, 2, N'Qinghai')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (158, 4, N'Mizoram')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (159, 4, N'Dadra and Nagar Haveli')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (160, 4, N'Arunachal Pradesh')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (161, 4, N'Tripura')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (162, 1, N'Amapa')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (163, 1, N'Acre')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (164, 4, N'Sikkim')
INSERT INTO [dbo].[State] ([StateID], [CountryID], [StateName]) VALUES (165, 4, N'Nagaland')
SET IDENTITY_INSERT [dbo].[State] OFF

3.Right click on Models folder --> Add --> ADO.NET Entity DataModel --> Name it --> Select EF designer from Database from Entity Data Model Wizard --> Select connection string and web.config --> click next --> Choose your database objects and settings(here table you created) and give name to model namespace--> click finish.
4.Add webform to solution by right click --> Add --> webform -->name it.
5.Now replace the aspx page code with below code.


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridView.aspx.cs" Inherits="CRUDUsingEF.Contacts" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>www.mitechdev.com</title>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <style type="text/css">
        input{max-width:150px;}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h3 class="text-info">Grid view Using EF</h3>
        <asp:GridView ID="gridview" runat="server" AutoGenerateColumns="false"
            DataKeyNames="ContactID,CountryID,StateID" CellPadding="10" CellSpacing="0"
            ShowFooter="true"
            CssClass="table table-responsive table-striped" OnRowCommand="gridview_RowCommand" OnRowCancelingEdit="gridview_RowCancelingEdit" OnRowDeleting="gridview_RowDeleting" OnRowEditing="gridview_RowEditing" OnRowUpdating="gridview_RowUpdating">
            <Columns>
                <asp:TemplateField>
                    <HeaderTemplate>Contact Person</HeaderTemplate>
                    <ItemTemplate><%#Eval("ContactPerson") %></ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox cssClass="form-control" ID="txtContactPerson" runat="server" Text='<%#Bind("ContactPerson") %>' />
                        <asp:RequiredFieldValidator ID="rfCPEdit" runat="server" ForeColor="Red" ErrorMessage="*"
                             Display="Dynamic" ValidationGroup="edit" ControlToValidate="txtContactPerson">Required</asp:RequiredFieldValidator>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox cssClass="form-control" ID="txtContactPerson" runat="server"></asp:TextBox><br />
                        <asp:RequiredFieldValidator ID="rfCP" runat="server" ErrorMessage="*"
                            ForeColor="Red" Display="Dynamic" ValidationGroup="Add" ControlToValidate="txtContactPerson">Required</asp:RequiredFieldValidator>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>Contact No</HeaderTemplate>
                    <ItemTemplate><%#Eval("ContactNo") %></ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox cssClass="form-control" ID="txtContactNo" runat="server" Text='<%#Bind("ContactNo") %>' />
                        <asp:RequiredFieldValidator ID="rfCNEdit" runat="server" ErrorMessage="*"
                            Display="Dynamic" ForeColor="Red" ValidationGroup="edit" ControlToValidate="txtContactNo">Required</asp:RequiredFieldValidator>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox cssClass="form-control" ID="txtContactNo" runat="server"></asp:TextBox><br />
                        <asp:RequiredFieldValidator ID="rfCN" runat="server" ErrorMessage="*"
                            ForeColor="Red" Display="Dynamic" ValidationGroup="Add" ControlToValidate="txtContactNo">Required</asp:RequiredFieldValidator>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>Country</HeaderTemplate>
                    <ItemTemplate><%#Eval("CountryName") %></ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList cssClass="form-control" ID="ddCountry" runat="server" AutoPostBack="true" 
                             OnSelectedIndexChanged="ddCountry_SelectedIndexChanged">
                            <asp:ListItem Text="Select Country" Value="0"></asp:ListItem>
                        </asp:DropDownList>
                        <asp:RequiredFieldValidator ID="rfCEdit" runat="server" ErrorMessage="*"
                            ForeColor="Red" Display="Dynamic" ValidationGroup="edit" ControlToValidate="ddCountry" InitialValue="0">
                            Required
                        </asp:RequiredFieldValidator>
                     </EditItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList cssClass="form-control" ID="ddCountry" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddCountry_SelectedIndexChanged">
                            <asp:ListItem Text="Select Country" Value="0"></asp:ListItem>
                        </asp:DropDownList>
                        <br />
                        <asp:RequiredFieldValidator ID="rfC" runat="server" ErrorMessage="*"
                            ForeColor="Red" Display="Dynamic" ValidationGroup="Add" ControlToValidate="ddCountry" InitialValue="0">Required</asp:RequiredFieldValidator>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>State</HeaderTemplate>
                    <ItemTemplate><%#Eval("StateName") %></ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList cssClass="form-control" ID="ddState" runat="server">
                            <asp:ListItem Text="Select State" Value="0"></asp:ListItem>
                        </asp:DropDownList>
                        <asp:RequiredFieldValidator ID="rfSEdit" runat="server" ErrorMessage="*"
                            ForeColor="Red" Display="Dynamic" ValidationGroup="edit" ControlToValidate="ddState" InitialValue="0">
                            Required
                        </asp:RequiredFieldValidator>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList cssClass="form-control" ID="ddState" runat="server">
                            <asp:ListItem Text="Select State" Value="0"></asp:ListItem>
                        </asp:DropDownList><br />
                        <asp:RequiredFieldValidator ID="rfS" runat="server" ErrorMessage="*"
                            ForeColor="Red" Display="Dynamic" ValidationGroup="Add" ControlToValidate="ddState"
                            InitialValue="0">Required</asp:RequiredFieldValidator>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:LinkButton ID="lbEdit" cssClass="btn btn-success" runat="server" CommandName="Edit">Edit</asp:LinkButton>
                        &nbsp;|&nbsp;
                        <asp:LinkButton ID="lbDelete" cssClass="btn btn-danger" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you confirm?')">Delete</asp:LinkButton>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:LinkButton ID="lbUpdate" cssClass="btn btn-success" runat="server" CommandName="Update" ValidationGroup="edit">Update</asp:LinkButton>
                        &nbsp;|&nbsp;
                        <asp:LinkButton ID="lbCancel" cssClass="btn btn-default" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:Button ID="btnInsert" cssClass="btn btn-success" runat="server" Text="Save" CommandName="Insert" ValidationGroup="Add" />
                    </FooterTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
6.Here, I took the grid templates to perform the operations.The design of grid look like below.

crud operations in gridview using entity framework

7.Now switch to gridview.aspx.cs file and add below methods,
1.To fetch and bind database data to gridview.
2.To implement cascading drop down list of country and state.
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //binds all contacts to grid
                LoadContacts();
            }
        }
        //fetch data from database and binds it to grid
        private void LoadContacts()
        {
            List allContacts = null;
            using (MydatabaseEntities dc = new MydatabaseEntities())
            {
                var contacts = (from a in dc.Contacts
                                join b in dc.Countries on a.CountryID equals b.CountryID
                                join c in dc.States on a.StateID equals c.StateID
                                select new
                                {
                                    a,
                                    b.CountryName,
                                    c.StateName
                                });
                if (contacts != null)
                {
                    allContacts = new List();
                    foreach (var i in contacts)
                    {
                        Contact c = i.a;
                        c.CountryName = i.CountryName;
                        c.StateName = i.StateName;
                        allContacts.Add(c);
                    }
                }
                if (allContacts == null || allContacts.Count == 0)
                {
                    allContacts.Add(new Contact());
                    gridview.DataSource = allContacts;
                    gridview.DataBind();
                    gridview.Rows[0].Visible = false;
                }
                else
                {
                    gridview.DataSource = allContacts;
                    gridview.DataBind();
                }
                if (gridview.Rows.Count > 0)
                {
                    DropDownList dd = (DropDownList)gridview.FooterRow.FindControl("ddCountry");
                    BindCountry(dd, PopulateCountry());
                }
            }
        }
        //fetches country dropdown data from database
        private List PopulateCountry()
        {
            using (MydatabaseEntities dc = new MydatabaseEntities())
            {
                return dc.Countries.OrderBy(a => a.CountryName).ToList();
            }
        }
        ////fetches states dropdownlist data from db
        private List PopulateState(int countryID)
        {
            using (MydatabaseEntities dc = new MydatabaseEntities())
            {
                return dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList();
            }
        }
        //binds countries list data to country dropdownlist
        private void BindCountry(DropDownList ddCountry, List country)
        {
            ddCountry.Items.Clear();
            ddCountry.Items.Add(new ListItem { Text = "Select Country", Value = "0" });
            ddCountry.AppendDataBoundItems = true;

            ddCountry.DataTextField = "CountryName";
            ddCountry.DataValueField = "CountryID";
            ddCountry.DataSource = country;
            ddCountry.DataBind();
        }
        //binds state dropdownlist data to state dropdown.
        private void BindState(DropDownList ddState, int countryID)
        {
            ddState.Items.Clear();
            ddState.Items.Add(new ListItem { Text = "Select State", Value = "0" });
            ddState.AppendDataBoundItems = true;

            ddState.DataTextField = "StateName";
            ddState.DataValueField = "StateID";
            ddState.DataSource = countryID > 0 ? PopulateState(countryID) : null;
            ddState.DataBind();
        }
        //this method fires when country dropdown list selection changes.
        //and binds respective state to state dropdownlist.
        protected void ddCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            //write code for cascade dropdown
            string countryID = ((DropDownList)sender).SelectedValue;
            var dd = (DropDownList)((System.Web.UI.WebControls.ListControl)(sender)).Parent.Parent.FindControl("ddState");
            BindState(dd, Convert.ToInt32(countryID));
        }


8.Now to perform CRUD operations on grid view create and implement below methods.
//inserts record into grid
        protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Insert")
            {
                Page.Validate("Add");
                if (Page.IsValid)
                {
                    var fRow = gridview.FooterRow;
                    TextBox txtContactPerson = (TextBox)fRow.FindControl("txtContactPerson");
                    TextBox txtContactNo = (TextBox)fRow.FindControl("txtContactNo");
                    DropDownList ddCountry = (DropDownList)fRow.FindControl("ddCountry");
                    DropDownList ddState = (DropDownList)fRow.FindControl("ddState");
                    using (MydatabaseEntities dc = new MydatabaseEntities())
                    {
                        dc.Contacts.Add(new Contact
                        {
                            ContactPerson = txtContactPerson.Text.Trim(),
                            ContactNo = txtContactNo.Text.Trim(),
                            CountryID = Convert.ToInt32(ddCountry.SelectedValue),
                            StateID = Convert.ToInt32(ddState.SelectedValue)
                        });
                        dc.SaveChanges();
                        LoadContacts();
                    }
                }
            }
        }
        //fetches the record from db based on record id
        protected void gridview_RowEditing(object sender, GridViewEditEventArgs e)
        {
            string countryID = gridview.DataKeys[e.NewEditIndex]["CountryID"].ToString();
            string stateID = gridview.DataKeys[e.NewEditIndex]["StateID"].ToString();
            gridview.EditIndex = e.NewEditIndex;
            LoadContacts();
            DropDownList ddCountry = (DropDownList)gridview.Rows[e.NewEditIndex].FindControl("ddCountry");
            DropDownList ddState = (DropDownList)gridview.Rows[e.NewEditIndex].FindControl("ddState");
            if (ddCountry != null && ddState != null)
            {
                BindCountry(ddCountry, PopulateCountry());
                ddCountry.SelectedValue = countryID;
                BindState(ddState, Convert.ToInt32(countryID));
                ddState.SelectedValue = stateID;
            }
        }
        //cancels the updation of record
        protected void gridview_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            //Cancel Edit Mode 
            gridview.EditIndex = -1;
            LoadContacts();
        }
        //updates the record on db
        protected void gridview_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Page.Validate("edit");
            if (!Page.IsValid)
            {
                return;
            }
            int contactID = (int)gridview.DataKeys[e.RowIndex]["ContactID"];
            TextBox txtContactPerson = (TextBox)gridview.Rows[e.RowIndex].FindControl("txtContactPerson");
            TextBox txtContactNo = (TextBox)gridview.Rows[e.RowIndex].FindControl("txtContactNo");
            DropDownList ddCountry = (DropDownList)gridview.Rows[e.RowIndex].FindControl("ddCountry");
            DropDownList ddState = (DropDownList)gridview.Rows[e.RowIndex].FindControl("ddState");
            using (MydatabaseEntities dc = new MydatabaseEntities())
            {
                var v = dc.Contacts.Where(a => a.ContactID.Equals(contactID)).FirstOrDefault();
                if (v != null)
                {
                    v.ContactPerson = txtContactPerson.Text.Trim();
                    v.ContactNo = txtContactNo.Text.Trim();
                    v.CountryID = Convert.ToInt32(ddCountry.SelectedValue);
                    v.StateID = Convert.ToInt32(ddState.SelectedValue);
                }
                dc.SaveChanges();
                gridview.EditIndex = -1;
                LoadContacts();
            }
        }
        //delete the selected record from grid
        protected void gridview_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int contactID = (int)gridview.DataKeys[e.RowIndex]["ContactID"];
            using (MydatabaseEntities dc = new MydatabaseEntities())
            {
                var v = dc.Contacts.Where(a => a.ContactID.Equals(contactID)).FirstOrDefault();
                if (v != null)
                {
                    dc.Contacts.Remove(v);
                    dc.SaveChanges();
                    LoadContacts();
                }
            }
        }

delete operation in gridview

9.For styling this grid i used twitter bootstrap css framework classes in grid.
10.Download source code this application from Github.

Conclusion:

I hope this article will help you .To get more updates please subscribe to this blog subscribe.