Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Create XML document in C# using LINQ XDocument Class

In this articles, I am going to explain you how to create XML document in C# using LINQ XDocument class. Below is step by step tutorial.

Namespace Required

Create an empty asp.net web application and add a webform to it.
Include below namespace.

How to extract text from PDF file using iTextSharp with C#

In this tutorial, I am going to explain you how to extract text from PDF file using iTextSharp with C# in ASP.NET. Below is step by step tutorial.

Creating ASP.NET Empty Application

Create an ASP.NET Empty WebForm project as shown below.
Go to FileNewProject. A new window will be open as shown below.
Now go to WebVisual Studio 2012 → select .NET Framework 4.5 → select ASP.NET Empty Web Application and give project name and click on OK.

Creating asp.net 4.5 empty project

Now, an asp.net empty project will be created. Add a new webform to application.

Installing iTextSharp

Now the next step is to add iTextSharp reference to your application. We can add reference by two ways.
First: Download from Internet
Click on the below link to download the dll.
https://github.com/itext/itextsharp Once file is downloaded, extract it, now you will find 6 more .rar file. Again extract itextsharp-dll-core.rar file, after that add reference of itextsharp.dll to your project.
or Second: Nuget Package Manager
Go to TOOLS → Library Package Manager → Manage NuGet Packages for Solution.. and a new window will open. Type and search for iTextSharp and click on Install button as shown below. Once installed successfully, you can check iTextSharp in references folder.

Adding iTextSharp
Installing iTextSharp

You can also install by using Package Manager Console.
Go to TOOLS → Library Package Manager → Package Manager Console → write Install-Package iTextSharp and press enter. This will install iTextSharp in application.

In aspx file

In designer file create two button controls, first button is used to generate pdf file and second button is used to extract text from pdf file. One textbox control to display extracted text from pdf. Designer file look like as shown below.

Aspx designer file
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
 
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
    <table>
        <tr>
            <td><b>Extract Text from PDF file using iTextSharp</b></td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnGeneratePDF" runat="server" Text="Generate PDF File" OnClick="btnGeneratePDF_Click" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnExtract" runat="server" Text="Extract Text From PDF File" OnClick="btnExtract_Click" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Style="width: 500px; min-height: 150px;"> 
                </asp:TextBox>
            </td>
        </tr>
    </table>
</div>
</form>
</body>
</html>

C# Code

Complete C# code is given below.

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
 
}
 
protected void btnGeneratePDF_Click(object sender, EventArgs e)
{
    if (File.Exists(Server.MapPath("Example.pdf")))
    {
        File.Delete(Server.MapPath("Example.pdf"));
    }
 
    // create pdf file and save it to the root directory of the application 
    FileStream fs = new FileStream(Server.MapPath("Example.pdf"), FileMode.Create);
 
    Document doc = new Document();
 
    PdfWriter.GetInstance(doc, fs);
 
    doc.Open();
 
    Paragraph page = new Paragraph("This is first page (page number 1)");
    doc.Add(page);
 
    Paragraph para1 = new Paragraph();
    Chunk c1 = new Chunk(@"This is first paragraph. This is first paragraph. This is first paragraph. This is first paragraph. This is first paragraph. This is first paragraph. This is first paragraph. This is first paragraph. This is first paragraph.");
    c1.SetBackground(BaseColor.YELLOW);
    para1.Add(c1);
    doc.Add(para1);
 
    Paragraph para2 = new Paragraph();
    Chunk c2 = new Chunk(@"This is second paragraph. This is second paragraph. This is second paragraph. This is second paragraph. This is second paragraph. This is second paragraph. This is second paragraph. This is second paragraph. This is second paragraph.");
    c2.SetBackground(BaseColor.GREEN);
    para2.Add(c2);
    doc.Add(para2);
 
    doc.Close();
}
 
protected void btnExtract_Click(object sender, EventArgs e)
{
    //string FilePath = @"H:\\Demo\\WebApplication1\\WebApplication1\\Example.pdf";
 
    string FilePath = Server.MapPath("Example.pdf");
 
    if (File.Exists(FilePath))
    {
        string ExtractedData = string.Empty;
 
        using (PdfReader reader = new PdfReader(FilePath))
        {
            ITextExtractionStrategy strategy = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
 
            // 1. if pdf document has only one page
            //here second parameter is PDF Page number
            ExtractedData = PdfTextExtractor.GetTextFromPage(reader, 1, strategy);
 
 
            /*// 2. if pdf ducument has more than one page
            // iterating through all pages
            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                ExtractedData = PdfTextExtractor.GetTextFromPage(reader, i, strategy);
            }*/
 
 
            /*// if pdf single page is having more than one paragraph
            // then split paragraph using newline
            ExtractedData = PdfTextExtractor.GetTextFromPage(reader, 1, strategy);
            string[] lines = ExtractedData.Split('\n');
            StringBuilder sb = new StringBuilder();
            foreach (string line in lines)
            {
                // 
            }*/
 
        }
        TextBox1.Text = ExtractedData;
    }
}
}
}

When you click on the Generate PDF File button, a PDF will be generated and will be saved at root directory of application. When you open pdf file, you will see 3 paragraph as shown below.

PDF file generated using iTextSharp

Now when you click on Extract Text From PDF File, all the text from page one will be extracted and displayed to the TextBox. You can iterate through all the pages using foor loop. Code is added and commented above.

Extract text from PDF using iTextSharp

Export DataTable to PDF file using iTextSharp and download/transmit at client machine

In this article, I am going to explain you how to export DataTable to PDF file using iTextSharp in C# and download or transmit at client machine. First, you need to download iTextSharp dll from the internet. Click on the below link to download the dll.
https://github.com/itext/itextsharp

Once file is downloaded, extract it, now you will find 6 more .rar file. Again extract itextsharp-dll-core.rar file, after that add reference of itextsharp.dll to your project.

Related Article

  1. How to export GridView data into PDF using iTextSharp in asp.net with C#
  2. Insert an image into PDF using iTextSharp with C# (C-Sharp)
  3. How to add meta information of PDF file using iTextSharp with C-Sharp
  4. How to extract images from a pdf file using C#.Net

In Code-Behind File

Add below nampespaces.

using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;

C# Code Snippet

Below is complete C# code to generate pdf file using dummy data table.

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
        ExportDataTableToPdfandDownloadAtClient();
    }
}

private void ExportDataTableToPdfandDownloadAtClient()
{
    // creating datatable and adding dumy data
    DataTable dtEmployee = new DataTable();
    dtEmployee.Columns.Add("EmpId", typeof(Int32));
    dtEmployee.Columns.Add("Name", typeof(string));
    dtEmployee.Columns.Add("Gender", typeof(string));
    dtEmployee.Columns.Add("Salary", typeof(Int32));
    dtEmployee.Columns.Add("Country", typeof(string));
    dtEmployee.Rows.Add(1, "Rahul", "Male", 60000, "India");
    dtEmployee.Rows.Add(2, "John", "Male", 50000, "USA");
    dtEmployee.Rows.Add(3, "Mary", "Female", 75000, "UK");
    dtEmployee.Rows.Add(4, "Mathew", "Male", 80000, "Australia");

    // creating document object
    iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(PageSize.A4);
    rec.BackgroundColor = new BaseColor(System.Drawing.Color.Olive);
    Document doc = new Document(rec);
    doc.SetPageSize(iTextSharp.text.PageSize.A4);
    PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
    doc.Open();

    //Creating paragraph for header
    BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    iTextSharp.text.Font fntHead = new iTextSharp.text.Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.ORANGE);
    Paragraph prgHeading = new Paragraph();
    prgHeading.Alignment = Element.ALIGN_LEFT;
    prgHeading.Add(new Chunk("Employee Details".ToUpper(), fntHead));
    doc.Add(prgHeading);

    //Adding paragraph for report generated by
    Paragraph prgGeneratedBY = new Paragraph();
    BaseFont btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    iTextSharp.text.Font fntAuthor = new iTextSharp.text.Font(btnAuthor, 8, 2, iTextSharp.text.BaseColor.BLUE);
    prgGeneratedBY.Alignment = Element.ALIGN_RIGHT;
    prgGeneratedBY.Add(new Chunk("Report Generated by : ASPArticles", fntAuthor));
    prgGeneratedBY.Add(new Chunk("\nGenerated Date : " + DateTime.Now.ToShortDateString(), fntAuthor));
    doc.Add(prgGeneratedBY);

    //Adding a line
    Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1)));
    doc.Add(p);

    //Adding line break
    doc.Add(new Chunk("\n", fntHead));

    //Adding  PdfPTable
    PdfPTable table = new PdfPTable(dtEmployee.Columns.Count);

    for (int i = 0; i < dtEmployee.Columns.Count; i++)
    {
        string cellText = Server.HtmlDecode(dtEmployee.Columns[i].ColumnName);
        PdfPCell cell = new PdfPCell();
        cell.Phrase = new Phrase(cellText, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#ffffff"))));
        cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#990000"));
        //cell.Phrase = new Phrase(cellText, new Font(Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(grdStudent.HeaderStyle.ForeColor)));
        //cell.BackgroundColor = new BaseColor(grdStudent.HeaderStyle.BackColor);
        cell.HorizontalAlignment = Element.ALIGN_CENTER;
        cell.PaddingBottom = 5;
        table.AddCell(cell);
    }

    //writing table Data
    for (int i = 0; i < dtEmployee.Rows.Count; i++)
    {
        for (int j = 0; j < dtEmployee.Columns.Count; j++)
        {
            table.AddCell(dtEmployee.Rows[i][j].ToString());
        }
    }

    doc.Add(table);
    doc.Close();
    writer.Close();
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;" + "filename=EmployeeDetails.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Write(doc);
    Response.End();
}

Below is the pdf file will be downloaded at client machine.

Export datatable to pdf file using itextsharp


DOWNLOAD SOURCE CODE

LINQ Take and TakeWhile Partitioning operators in C#

LINQ Take and TakeWhile Partitioning operators in C#

In this article, I am going to explain you LINQ Take and TakeWhile partitioning operators in C#. I have already explained Skip and SkipWhile operators in detail. Below is the four partitioning operators. Partitioning operators split the collection into two parts and returns one part only.
1) Skip
2) SkipWhile  (click here to read about Skip and SkipWhile)
3) Take - It takes element up-to specified position starting from first element in collection or sequence.
4) TakeWhile - It take elements from given collection until the specified condition is true.

Let's understand the these operators with examples.

Using Take Partitioning Operator In LINQ

Example 1

Let's apply Take operator on a string array which contains some words. Here Take operator will Take first 4 element from collection and return.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
var takeFirstFourWords = words.Take(4);
foreach (var word in takeFirstFourWords)
{
    Console.WriteLine(word);
}
Console.ReadKey();
//OUTPUT:
//Five
//Four
//One
//Three

Example 2

Here, it will return first 5 numbers.

int[] numbers = { 9, 8, 6, 7, 2, 5, 4, 1, 3, 0 };
var takeFirstFiveNumbers = numbers.Take(5);
foreach (var number in takeFirstFiveNumbers)
{
    Console.WriteLine(number);
}
Console.ReadKey();
//OUTPUT:
//9
//8
//6
//7
//2

Example 3

Take and TakeWhile operator do not support in query syntax but still we can use Take on query variable. Consider the example given below, we need 2 words from first 4 words whose length is greater than 4.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };

var stringNumbers = from s in words
                              where s.Length > 4 // find words whose length is grater than 4
                              select s;

Console.WriteLine("words whose length is grater than 4");
foreach (var word in stringNumbers)
{
    Console.WriteLine(word);
}
/*
OUTPUT:
Three
Eight
Seven
*/

var takeFirstTwoWords = stringNumbers.Take(2); //take first 2 words
Console.WriteLine("After taking two words");
foreach (var word in takeFirstTwoWords)
{
    Console.WriteLine(word);
}
Console.ReadKey();
/*
OUTPUT:
Three
Eight
*/

Using TakeWhile Partitioning Operator In LINQ

Example 1

Let's understand TakeWhile operator with example. Consider the string array of words given below. Here first 3 elements are "Five", "Four", "One" and their length is less than 5. So, according to TakeWhile definition, for the first 3 elements condition is true because there length is less than 5, but from 4th element that is "Three" here length is equal to 5 that means if length is equal to 5 then condition becomes false, so TakeWhile will return those element for which condition was true.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
//length is               4         4         3         5           4         5          3         5           3         4
//length < 5           true     true     true     false
var data = words.TakeWhile(x => x.Length < 5);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//Five
//Four
//One

Example 2

Here, we will use same example as shown above, in above example we used (<) less than operator, now we will use (>) greater than operator. Here the first element is "Five" whose length is equal to 4, but it is less than 5, so condition becomes false at first element only because we are checking for the element whose length is greater than 5. So, if condition becomes false at first statement only then it will return an empty collection.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
//length is               4         4         3         5           4         5          3         5           3         4
//length > 5           false    
var data = words.TakeWhile(x => x.Length > 5);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//No Output

Example 3

Here, in below example first 5 elements when divided by 5, they have some Remainder but from 6th element that is '5' which has Remainder 0, here the condition becomes false because we are checking for Remainder should not be equal to zero, so it will return those element for which condition was true.

int[] numbers = { 9, 8, 6, 7, 2, 5, 4, 1, 3, 0 };

var data = numbers.TakeWhile(x => x % 5 != 0);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//9
//8
//6
//7
//2

Using TakeWhile With Index

We can use, second overload of TakeWhile. It passes index of each elements. In below example, it take all the element till the length of elements is greater than it's index. Here, condition becomes false at 5th element("Nine"), so it will return elements for which condition was true.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
// length is              4         4         3         5           4         5         3         5           3         4
// index  is              0         1         2         3           4         5         6         7           8         9
// length > index   true     true     true     true       false      -         -          -            -          -
var data = words.TakeWhile((x,i) => x.Length > i);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//Five
//Four
//One
//Three

LINQ Skip and SkipWhile Partitioning operators in C#

LINQ Skip and SkipWhile Partitioning operators in C#

In this article, I am going to explain you LINQ Skip and SkipWhile partitioning operators in C#. Below is the four partitioning operators in C#. Partitioning operators split the collection into two parts and returns one part only.
1) Skip - It skips element up-to specified position starting from first element in collection.
2) SkipWhile – It skip elements in the collection till the specified condition is true. It returns a new collection that includes all the remaining elements once the specified condition becomes false for any element.
3) Take 4) TakeWhile  (click here to read about Take and TakeWhile)

Let's understand the these operators with examples.

Using Skip Partitioning Operator In LINQ

Example 1

Let's apply Skip operator on a string array which contains some words. Here Skip operator will skip first 4 element from collection and returns remaining element from array.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
var skipFirstFourWords = words.Skip(4);
foreach (var word in skipFirstFourWords)
{
    Console.WriteLine(word);
}
Console.ReadKey();
//OUTPUT:
//Nine
//Eight
//Six
//Seven
//Two
//Zero

Example 2

int[] numbers = { 9, 8, 6, 7, 2, 5, 4, 1, 3, 0 };
var skipFirstFiveNumbers = numbers.Skip(5);
foreach (var number in skipFirstFiveNumbers)
{
    Console.WriteLine(number);
}
Console.ReadKey();
//OUTPUT:
//5
//4
//1
//3
//0

Example 3

Skip and SkipWhile operator do not support in query syntax but still we can use skip and skip on query variable. Consider the example given below, we need to skip 2 words from first 4 words whose length is greater than 4.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };

var stringNumbers = from s in words
                              where s.Length > 4 // find words whose length is grater than 4
                              select s;

Console.WriteLine("words whose length is grater than 4");
foreach (var word in stringNumbers)
{
    Console.WriteLine(word);
}
/*
OUTPUT:
Three
Eight
Seven
*/

var skipFirstTwoWords = stringNumbers.Skip(2); //skip first 2 words
Console.WriteLine("After skipping two words");
foreach (var word in skipFirstTwoWords)
{
    Console.WriteLine(word);
}
Console.ReadKey();
/*
OUTPUT:
Seven
*/

Example 4

In this example, we will use two List object of type Employee and Department as shown below. Here, we need to skip first 2 employees of Department 'IT' using query syntax. It is similar to Example 3.

 class Program
 {
     class Employee
     {
         public int Id { get; set; }
         public string Name { get; set; }
         public int Salary { get; set; }
         public int DeptId { get; set; }
     }
     class Department
     {
         public int Id { get; set; }
         public string Name { get; set; }
     }
     static void Main(string[] args)
     {
         // list of type Employee
         List<Employee> employee = new List<Employee>(){
             new Employee { Id=1, Name = "Rahul", Salary=50000, DeptId=101},
             new Employee { Id=2, Name = "John", Salary=10000, DeptId=102},
             new Employee { Id=3, Name = "Mike", Salary=4000, DeptId=103},
             new Employee { Id=4, Name = "Mary", Salary=75000, DeptId=101},
             new Employee { Id=5, Name = "Sachin", Salary=6500, DeptId=102},
             new Employee { Id=6, Name = "Deepak", Salary=80000, DeptId=103},
             new Employee { Id=7, Name = "Mithoon", Salary=10000, DeptId=101},
             new Employee { Id=8, Name = "Hrithik", Salary=72000, DeptId=102},
             new Employee { Id=9, Name = "Savio", Salary=10000, DeptId=103},
             new Employee { Id=10, Name = "Yogesh", Salary=90000, DeptId=101}
         };
         // list of type Department
         List<Department> department = new List<Department>(){
             new Department { Id=101, Name = "IT"},
             new Department { Id=102, Name = "HR"}, 
             new Department { Id=103, Name = "Payroll"}, 
             new Department { Id=104, Name = "Sales"}, 
             new Department { Id=105, Name = "Production"},
         };

         var data = from e in employee
                    join d in department
                    on e.DeptId equals d.Id
                    where d.Name == "IT"
                    select new
                    {
                        eId = e.Id,
                        eName = e.Name,
                        dName = d.Name
                    };
         Console.WriteLine("---------All employees in department IT---------");
         foreach (var v in data)
         {
             Console.WriteLine("Employee Id - " + v.eId + ", Employee Name - " + v.eName + ", Department Name - " + v.dName);
         }

         Console.WriteLine("---------Now skip first two employees in department IT---------");
         var afterSkip = data.Skip(2);
         foreach (var v in afterSkip)
         {
             Console.WriteLine("Employee Id - " + v.eId + ", Employee Name - " + v.eName + ", Department Name - " + v.dName);
         }
         Console.ReadKey();

         //OUTPUT:
         //---------All employees in department IT---------
         //Employee Id - 1, Employee Name - Rahul, Department Name - IT
         //Employee Id - 4, Employee Name - Mary, Department Name - IT
         //Employee Id - 7, Employee Name - Mithoon, Department Name - IT
         //Employee Id - 10, Employee Name - Yogesh, Department Name - IT
         //---------Now skip first two employees in department IT---------
         //Employee Id - 7, Employee Name - Mithoon, Department Name - IT
         //Employee Id - 10, Employee Name - Yogesh, Department Name - IT
     }
 }

Using SkipWhile Partitioning Operator In LINQ

Example 1

Let's understand SkipWhile operator with example. Consider the string array of words given below. Here first 3 elements are "Five", "Four", "One" and their length is less than 5, so according to SkipWhile definition, first 3 elements satisfy condition and condition becomes true but from 4th element that is "Three" here length is equal to 5 that means if length is equal to 5 then condition becomes false, so SkipWhile will return remaining operator once condition is false.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
//length is               4         4         3         5           4         5          3         5           3         4
//length < 5           true     true     true     false
var data = words.SkipWhile(x => x.Length < 5);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//Three
//Nine
//Eight
//Six
//Seven
//Two
//Zero

Example 2

Here, we will use same example as shown above, in above example we used (<) less than operator, now we will use (>) greater than operator. Here the first element is "Five" whose length is equal to 4, but it is less than 5, so condition becomes false at first element only because we are checking for element whose length is greater than 5, so according to definition, it will returns remaining element from element where condition become false.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
//length is               4         4         3         5           4         5          3         5           3         4
//length > 5           false    
var data = words.SkipWhile(x => x.Length > 5);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//Five
//Four
//One
//Three
//Nine
//Eight
//Six
//Seven
//Two
//Zero

Example 3

Here, in below example first 5 elements when divided by 5, they have some Remainder but from 6th element that is '5' which has Remainder 0, here the condition becomes false because we are checking for Remainder should not be equal to zero, so it will return all the remaining elements from 6th element.

int[] numbers = { 9, 8, 6, 7, 2, 5, 4, 1, 3, 0 };

var data = numbers.SkipWhile(x => x % 5 != 0);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//5
//4
//1
//3
//0

Using SkipWhile With Index

Example 1

We can use, second overload of SkipWhile. It passes index of each elements. In below example, it skips all the element till the length of elements is greater than it's index. Here, condition becomes false at 5th element("Nine"), so it will return remaining elements.

string[] words = { "Five", "Four", "One", "Three", "Nine", "Eight", "Six", "Seven", "Two", "Zero" };
// length is              4         4         3         5           4         5         3         5           3         4
// index  is              0         1         2         3           4         5         6         7           8         9
// length > index   true     true     true     true       false      -         -          -            -          -
var data = words.SkipWhile((x,i) => x.Length > i);
foreach (var d in data)
{
    Console.WriteLine(d);
}
Console.ReadKey();
//OUTPUT:
//Nine
//Eight
//Six
//Seven
//Two
//Zero

Example 4

In this example, we will use two List object of type Employee and Department as used in Example 4 of Skip Operator. Here, we will fetch all employees of Department 'IT' using query syntax.

var data = from e in employee
           join d in department
           on e.DeptId equals d.Id
           where d.Name == "IT"
           select new
           {
               eId = e.Id,
               eName = e.Name,
               dName = d.Name
           };
Console.WriteLine("---------All employees in department IT---------");
foreach (var v in data)
{
    Console.WriteLine("Employee Id - " + v.eId + ", Employee Name - " + v.eName + ", Department Name - " + v.dName);
}
//OUTPUT:
//---------All employees in department IT---------
//Employee Id - 1, Employee Name - Rahul, Department Name - IT
//Employee Id - 4, Employee Name - Mary, Department Name - IT
//Employee Id - 7, Employee Name - Mithoon, Department Name - IT
//Employee Id - 10, Employee Name - Yogesh, Department Name - IT

Now, we will apply SkipWhile operator on Name column whose length is greater than 4. Here in above output Employee Name - Rahul , Rahul has length greater than 4, so condition is true here, but for Mary length is not greater than 4, so condition becomes false here.

Console.WriteLine("---------Now use SkipWhile on Name column---------");
var afterSkipWhile = data.SkipWhile(x => x.eName.Length > 4);
foreach (var v in afterSkipWhile)
{
    Console.WriteLine("Employee Id - " + v.eId + ", Employee Name - " + v.eName + ", Department Name - " + v.dName);
}
Console.ReadKey();
//---------Now use SkipWhile on Name column---------
//Employee Id - 4, Employee Name - Mary, Department Name - IT
//Employee Id - 7, Employee Name - Mithoon, Department Name - IT
//Employee Id - 10, Employee Name - Yogesh, Department Name - IT

How to export DataTable to CSV file in C#

In this article, I am going to explain how to export DataTable values to Comma Separated Value (CSV) excel file using C#.Net. A CSV file contains data with columns separated by comma. If you open a CSV file using Excel, then column and row data will be automatically filled in excel cells.

Below images shows how the CSV file look like when you open CSV file in text editor and in Excel.

CSV File GeneratedOpen in NotepadOpen in Excel
C# CSV file generated How to create CSV file in C# Export datatable in CSV file using C#

Related Articles

How to insert bulk of records from a text file in SQL-Server

Creating DataTable

First of all create a dummy DataTable in C# by using the code given below.

DataTable dt = new DataTable();
dt.Columns.Add("EmpId", typeof(Int32));
dt.Columns.Add("EmpName", typeof(string));
dt.Columns.Add("EmpCountry", typeof(string));
dt.Rows.Add(1, "Rahul", "India");
dt.Rows.Add(2, "John", "USA");
dt.Rows.Add(3, "Mary", "UK");
dt.Rows.Add(4, "Mathew", "Australia");

Export C# DataTable to CSV File

Below is the C# code to convert DataTable to CSV file in C#.

IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
                                  Select(column => column.ColumnName);

StringBuilder sb = new StringBuilder();

sb.AppendLine(string.Join(",", columnNames));

foreach (DataRow row in dt.Rows)
{
    string[] fields = row.ItemArray.Select(field => field.ToString()).
                                    ToArray();
    sb.AppendLine(string.Join(",", fields));
}

File.WriteAllText("E:\\Employee.csv", sb.ToString());

ASP.Net Query String to pass data from one page (WebForm) to another page

In this article, we are going to learn how to pass data from one page (aspx page) to another page using Query String in ASP.Net. There are different types of technique available in ASP.Net to pass data from one webform to another webform. Below is the list.
1. Query String (We will discuss in this article)
2. Cross Page Postback (We will discuss in later article)
3. Context.Handler object We will discuss in later article)

Let's understand Query String with an example. First create two webforms i.e. WebForm1.aspx and WebForm2.aspx. In the first webform create two TextBox controls to capture First Name and Last Name and one Button control to send data from WebForm1.aspx to WebForm2.aspx. Below is the designer for first page.

<table>
   <tr>
      <td>FirstName</td>
      <td><asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></td>
   </tr>
   <tr>
      <td>LastName</td>
      <td><asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td>
   </tr>
   <tr>
      <td colspan="2">
       <asp:Button id="btnSend" runat="server" Text="Send Data" OnClick="btnSend_Click"/>
      </td>
   </tr>
</table>

Now, in the second webform create two Label controls to display First Name and Last Name. Below is the designer for second page.

<table>
   <tr>
      <td>FirstName: </td>
      <td><asp:Label ID="lblFirstName" runat="server"></asp:Label></td>
   </tr>
   <tr>
      <td>LastName: </td>
      <td><asp:Label ID="lblLastName" runat="server"></asp:Label></td>
   </tr>
</table>

Now, we will pass data from webform1 to webform2 onclick on Send Button. As you can see in below code, to pass data we need to append ?(question mark) after the destination url i.e. WebForm2.aspx and after ?(question mark) append key and its value. If you want to pass more than one key/value pair then use & (ampersand) as shown below.

// In webform1.aspx.cs
protected void btnSend_Click(object sender, EventArgs e)
{
   Response.Redirect("~/WebForm2.aspx?FirstName=" +txtFirstName.Text+ "&LastName=" + txtLastName.Text);
}

Now on click of submit button, data will be passed to WebForm2.aspx. To retrieve data from URL, use below code in WebForm2.

// In webform2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
   lblFirstName.Text=Request.QueryString["FirstName"];
   lblLastName.Text = Request.QueryString["LastName"];

   // or you can specify index position
  // lblFirstName.Text = Request.QueryString[0];
  // lblLastName.Text = Request.QueryString[1];
}

You can see in below figure we have passed two key/value pair i.e FirstName and LastName. Data is passed trough the url.

Query String before passing data
Query String after passing data

In above example, we have passed FirstName as 'Sachin' and LastName as 'Tendulkar' and we were able to retrieve the values correctly. Now pass FirstName as 'Sachin & Rahul' and LastName as 'Tendulkar'. Here we got FirstName as 'Sachin' and LastName as 'Tendulkar' because we have used & (ampersand) in first TextBox. You can see in second image, url that formed is containing & (ampersand) two times. So FirstName will be retrieved as 'FirstName=Sachin%20' , here %20 is the space and LastName as 'LastName=Tendulkar' but our requirement is correctly retrieve first parameter as 'Sachin & Rahul'.

Query String with special symbol
Query String with special symbol output

To correct problem with &(ampersand), we can Encode the URL as shown below.

protected void btnSend_Click(object sender, EventArgs e)
{
    Response.Redirect("~/WebForm2.aspx?FirstName=" +
        Server.UrlEncode(txtFirstName.Text) + "&LastName=" + Server.UrlEncode(txtLastName.Text));
}

Now you can see in below figure. %20 is replaced by +(plus) and &(ampersand) is replaced by %26 using UrlEncode. Here we are able to retrieve values correctly.

Query String with url encode

We can use following code to retrieve the parameters.

protected void Page_Load(object sender, EventArgs e)
{
    for (int i = 0; i < Request.QueryString.Count; i++)
    {
        string Result = Request.QueryString[i];
    }
  
  // you can check null condition also
    if (!string.IsNullOrEmpty(Request.QueryString["FirstName"]))
    {
        lblFirstName.Text = Request.QueryString["FirstName"];
    }
}

More About Query Strings

1. Query strings are common way to send data from one page to another page.
2. Query strings are name/value collection pairs.
3. Query strings are appended to the page url.
4. ?(question mark), indicates the beginning of a query string and it's value.
5. It is possible to use more than one query string. The first query string is specified using the ?(question mark). Subsequent query strings can be appended to the URL using the &(ampersand) symbol.
6. To read the query string value, use Request object's QueryString property.

Disadvantages of Query Strings

1. There is a limit on the Query string length. Hence, Query strings cannot be used to send very long data.
2. Query strings are visible to the user, it should not be used to send sensitive information, unless it is encrypted.

ASP.Net GridView CRUD operations with Button controls outside of GridView control

In this article, we are going to learn CRUD operations that is insert, select, edit, update and delete with asp.net gridview control using sql stored procedure. I have already explained CRUD operations with stored procedure in one of my article, but in this article CRUD (Create, Read, Update, Delete) buttons will be residing outside of GridView control. You can see in below figures, button controls are residing below the gridview controls.

Crud operations in asp.net

Related Articles

  1. Insert, update, delete, crud operation in ASP.Net GridView with C# using Stored Procedure
  2. LINQ to SQL: GridView select, insert, update and delete using C# with ASP.Net

Creating SQL Table

First, we need to create two database tables. First for storing different City and second for storing employee's details. Below is the script to create table.

--creating city table
create table tblCity
(
Id int identity primary key,
Name varchar (50) null,
)
go
--inserting record into city table
insert into tblCity values('Mumbai')
insert into tblCity values('Delhi')
insert into tblCity values('London')
insert into tblCity values('New York')
go
--creating employee table
create table tblEmployee
(
Id int identity primary key,
Name varchar (50) null,
Gender varchar (10) null,
EMail varchar (25) null,
CityId int
)

Creating Standard Procedure

Also, we need to create stored procedure for different CRUD operations.

create procedure proc_Employee
@Action varchar(10)=null,
@Id int=null,
@Name varchar(50)=null,
@Gender varchar(10)=null,
@EMail varchar(25)=null,
@CityId int=null
as
begin
   if(@Action='Select')
      begin
       --to display all the record
       select e.Id,e.Name,e.Gender,e.EMail,c.Name as City from tblEmployee e
       join tblCity c on e.CityId=c.id
      end
   else if(@Action='Add')
     begin
      --to add a new record
      insert into tblEmployee values (@Name,@Gender,@EMail,@CityId) 
     end
   else if(@Action='Update')
     begin
      --to update the existing record
      update tblEmployee set Name=@Name,@Gender=@Gender,EMail=@EMail,CityId=@CityId where Id=@Id 
     end

   else if(@Action='Delete')
     begin
      --to delete a record
      delete from  tblEmployee where Id=@Id 
     end
   else if(@Action='GetCity')
     begin
      --to get all the city for binding dropdown control
      select Id,Name from tblCity
     end
end 

Creating Connection In Web.Config File

Write your database connection string in web.config file within <connectionStrings> tag.

<configuration>
  <connectionStrings>
<add name="MyConnString" connectionString="server=XXXX;database=XXXX;uid=XXXX;password=XXXX;" 
    providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>

In Designer File

CSS For Buttons

In designer file, add css for button controls.

<head runat="server">
    <title></title>
    <style type="text/css">
        .button
        {
            border-radius: 0.5em;
            color: white;
            padding: 7px;
            background-color: #329bd8;
            text-transform: uppercase;
            font-weight: bold;
            width: 80px;
        }
        .button:hover
        {
            background-color: transparent;
            border: 0.15em #329bd8 solid;
            color: #329bd8;
        }
    </style>
</head>

Creating Gridview Control

Next step is create a GridView control gridEmployee with 5 columns. Generate OnPageIndexChanging event and DataKeyNames for storing Employee's ID. Create 5 button controls for Add, Edit, Update, Delete and Cancel purpose.

<form id="form1" runat="server">
 <div>
   <table>
     <tr>
     <td>
       <asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
     </td>
     </tr>
     <tr>
     <td>
      <asp:GridView ID="gridEmployee" runat="server" PageSize="5" AutoGenerateColumns="false" 
          ShowFooter="true" AllowPaging="true" BackColor="White" BorderColor="#CC9966" 
          BorderStyle="None" BorderWidth="5px" CellPadding="4" 
          OnPageIndexChanging="gridEmployee_PageIndexChanging" Width="540px"
          DataKeyNames="Id">
          <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
          <RowStyle BackColor="White"/>
          <EditRowStyle BackColor="#FFFFCC" ForeColor="#330099" />
          <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
          <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
          <HeaderStyle BackColor="#329bd8" Font-Bold="True" ForeColor="White"/>
          <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="chkRow" runat="server"></asp:CheckBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name")%>'> </asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="etxtName" runat="server" Text='<%#Eval("Name")%>'> </asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="ftxtName" runat="server"> </asp:TextBox>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Gender">
                <ItemTemplate>
                    <asp:Label ID="lblGender" runat="server" Text='<%#Eval("Gender")%>'> </asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:DropDownList ID="eddlGender" runat="server">
                        <asp:ListItem Value="-Select-">-Select-</asp:ListItem>
                        <asp:ListItem Value="Male">Male</asp:ListItem>
                        <asp:ListItem Value="Female">Female</asp:ListItem>
                    </asp:DropDownList>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:DropDownList ID="fddlGender" runat="server">
                        <asp:ListItem Value="-Select-">-Select-</asp:ListItem>
                        <asp:ListItem Value="Male">Male</asp:ListItem>
                        <asp:ListItem Value="Female">Female</asp:ListItem>
                    </asp:DropDownList>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="EMail">
                <ItemTemplate>
                    <asp:Label ID="lblEMail" runat="server" Text='<%#Eval("EMail")%>'> </asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="etxtEMail" runat="server" Text='<%#Eval("EMail")%>'> </asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="ftxtEMail" runat="server"> </asp:TextBox>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City">
                <ItemTemplate>
                    <asp:Label ID="lblCity" runat="server" Text='<%#Eval("City")%>'> </asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:DropDownList ID="eddlCity" runat="server">
                    </asp:DropDownList>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:DropDownList ID="fddlCity" runat="server">
                    </asp:DropDownList>
                </FooterTemplate>
            </asp:TemplateField>
          </Columns>
      </asp:GridView>
     </td>
     </tr>
     <tr>
     <td>
       <table align="center">
         <tr style="width:500px;">
           <td>
               <asp:Button ID="btnAdd" runat="server" Text="Add" CssClass="button" OnClick="btnAdd_Click" />
           </td>
           <td>
               <asp:Button ID="btnEdit" runat="server" Text="Edit" CssClass="button" OnClick="btnEdit_Click" />
               <asp:Button ID="btnESave" runat="server" Text="Update" CssClass="button" OnClick="btnESave_Click" />
           </td>
           <td>
               <asp:Button ID="btnDelete" runat="server" Text="Delete" CssClass="button" OnClick="btnDelete_Click" />
           </td>
           <td>
               <asp:Button ID="btnCancel" runat="server" Text="Cancel" CssClass="button" OnClick="btnCancel_Click" />
           </td>
         </tr>
       </table>
     </td>
     </tr>
   </table>
 </div>
</form>

Namespaces Used

Include the below Namespaces.

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

Complete C# Code

On the Page_Load event, we are calling GetCity() method which will fetch city data from tblCity table and store city data into static dataset dsCity so that we can use it later.

Next method is BindGrid() which will execute the stored procedure with Select action to fetch all employee's record. If no record is found then we are adding new row to empty dataset and binding it to GridView. Also we are binding City DropDownList in footer row using static dataset dsCity.

As footer row is always enabled, on click of Add button, btnAdd_Click event get fired. We are using GridView.FooterRow.FindControl() to find required TextBox and DropDownList controls and perform server side validation, if validation is successful then executing the stored procedure with Add action to save record into database.

Now, the next step is to Edit a record, we can edit only a single record at a time. We are storing editindex of required row in ViewState so that we can use later while updating the record. We are binding City DropDownList while editing using static dataset dsCity. Also disabling the CheckBox control.

On click of Update button, btnESave_Click event get fired. We are retrieving current row index using ViewState. After that retrieving Employee's Id using GridView.DataKeys. GridView.Rows[editindex].FindControl() is used find the respective TextBox and DropDownList controls. After that, we are calling stored procedure to update the record.

The last step is to Delete the record. Here, we can delete as many records we want by selecting CheckBox control. Main important thing while deleting is to fetch Employee's Id using editindex.

public partial class WebForm1 : System.Web.UI.Page
{
    //retrieving connection string from web.config file
    string MyConnString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
    SqlConnection con = null;
    SqlCommand cmd = null;
    public static DataSet dsCity=null;
    int editindex = -1;
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            GetCity();
            BindGrid();
            // hide Update button on page load
            btnESave.Visible = false;             
        }
    }
 
    private void GetCity()
    {
        con = new SqlConnection(MyConnString);
        cmd = new SqlCommand("proc_Employee", con);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
 
        // call the GetCity task to get all Cities
        cmd.Parameters.AddWithValue("@Action", "GetCity");
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        sda.Fill(ds);
 
        dsCity = ds.Copy(); // copy city data into static dataset         
    }
 
    private void BindGrid()
    {
        con = new SqlConnection(MyConnString);
        cmd = new SqlCommand("proc_Employee", con);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
        // call the select task to get all data
        cmd.Parameters.AddWithValue("@Action", "Select");
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        sda.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            gridEmployee.DataSource = ds;
            gridEmployee.DataBind();
        }
        else
        {
            // add new row when the dataset is having zero record
            ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
            gridEmployee.DataSource = ds;
            gridEmployee.DataBind();
            gridEmployee.Rows[0].Visible = false;
        }
 
        // find the FooterRow City dropdown and populate it from static dataset
        DropDownList fddlCity = (DropDownList)gridEmployee.FooterRow.FindControl("fddlCity");
        if (dsCity.Tables[0].Rows.Count > 0)
        {
            fddlCity.DataSource = dsCity.Tables[0];
            fddlCity.DataTextField = "Name";
            fddlCity.DataValueField = "Id";
            fddlCity.DataBind();
            fddlCity.Items.Insert(0, "-Select-");
        }
    }
 
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        TextBox ftxtName = (TextBox)(gridEmployee.FooterRow.FindControl("ftxtName"));
        DropDownList fddlGender = (DropDownList)(gridEmployee.FooterRow.FindControl("fddlGender"));
        TextBox ftxtEMail = (TextBox)(gridEmployee.FooterRow.FindControl("ftxtEMail"));
        DropDownList fddlCity = (DropDownList)(gridEmployee.FooterRow.FindControl("fddlCity"));
 
        if (ftxtName.Text.Trim() == string.Empty)
        {
            lblMessage.Text = "Please enter Name";
            ftxtName.Focus();
            return;
        }
        if (fddlGender.SelectedIndex==0)
        {
            lblMessage.Text = "Please select Gender";
            fddlGender.Focus();
            return;
        }
        if (!Regex.IsMatch(ftxtEMail.Text.Trim(), @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
        , RegexOptions.IgnoreCase))
        {
            lblMessage.Text = "Please enter valid EMail";
            ftxtEMail.Focus();
            return;
        }
        if (fddlCity.SelectedIndex==0)
        {
            lblMessage.Text = "Please select City";
            fddlCity.Focus();
            return;
        }
 
        con = new SqlConnection(MyConnString);
        cmd = new SqlCommand("proc_Employee", con);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
        // call the select task to get all data
        cmd.Parameters.AddWithValue("@Action", "Add");
        cmd.Parameters.AddWithValue("@Name", ftxtName.Text.Trim());
        cmd.Parameters.AddWithValue("@Gender", fddlGender.SelectedItem.Text);
        cmd.Parameters.AddWithValue("@EMail", ftxtEMail.Text.Trim());
        cmd.Parameters.AddWithValue("@CityId", fddlCity.SelectedItem.Value);          
        cmd.ExecuteNonQuery();
        con.Close();
        BindGrid();           
        lblMessage.Text = "Record saved successfully";
    }
 
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        int rowCount = 0;
        foreach (GridViewRow gvrow in gridEmployee.Rows)
        {
            CheckBox chkRow = (CheckBox)gvrow.FindControl("chkRow");
            if (chkRow.Checked && chkRow != null)
            {
                //finding rowindex for edit
                editindex = gvrow.RowIndex;
                rowCount++;
                if (rowCount>1)
                {
                    break;
                }
            }
        }
        if (rowCount>1)
        {
            lblMessage.Text = "Please select single record to Edit";
        }
        else if(rowCount==0)
        {
            lblMessage.Text = "Please select record to Edit";
        }
        else
        {
            ViewState["editindex"] = editindex;
 
            gridEmployee.EditIndex = editindex;
            BindGrid();
 
            // bind city dropdown while editing
            DropDownList eddlCity = (DropDownList)(gridEmployee.Rows[editindex].FindControl("eddlCity"));
            if (dsCity.Tables[0].Rows.Count > 0)
            {
                eddlCity.DataSource = dsCity.Tables[0];
                eddlCity.DataTextField = "Name";
                eddlCity.DataValueField = "Id";
                eddlCity.DataBind();
                eddlCity.Items.Insert(0, "-Select-");
            }
 
            // disable all row checkboxes while editing
            foreach (GridViewRow gvrow in gridEmployee.Rows)
            {
                CheckBox chkRow = (CheckBox)gvrow.FindControl("chkRow");
                chkRow.Enabled = false;
            }
 
            //hide footer row while editing
            gridEmployee.FooterRow.Visible = false;
 
            // hide and disable respective buttons
            btnAdd.Enabled = false;
            btnEdit.Visible = false;
            btnESave.Visible = true;
            btnDelete.Enabled = false;            
        }
    }
 
    protected void btnESave_Click(object sender, EventArgs e)
    {
        // retrieving current row edit index from viewstate
        editindex= Convert.ToInt32(ViewState["editindex"].ToString());
 
        int Id = Convert.ToInt32(gridEmployee.DataKeys[editindex].Values["Id"].ToString());
        TextBox etxtName = (TextBox)gridEmployee.Rows[editindex].FindControl("etxtName");
        DropDownList eddlGender = (DropDownList)(gridEmployee.Rows[editindex].FindControl("eddlGender"));
        TextBox etxtEMail = (TextBox)(gridEmployee.Rows[editindex].FindControl("etxtEMail"));
        DropDownList eddlCity = (DropDownList)(gridEmployee.Rows[editindex].FindControl("eddlCity"));
 
        if (etxtName.Text.Trim() == string.Empty)
        {
            lblMessage.Text = "Please enter Name";
            etxtName.Focus();
            return;
        }
        if (eddlGender.SelectedIndex == 0)
        {
            lblMessage.Text = "Please select Gender";
            eddlGender.Focus();
            return;
        }
        if (!Regex.IsMatch(etxtEMail.Text.Trim(), @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
        , RegexOptions.IgnoreCase))
        {
            lblMessage.Text = "Please enter valid EMail";
            etxtEMail.Focus();
            return;
        }
        if (eddlCity.SelectedIndex == 0)
        {
            lblMessage.Text = "Please select City";
            eddlCity.Focus();
            return;
        }
 
        con = new SqlConnection(MyConnString);
        cmd = new SqlCommand("proc_Employee", con);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
        // call the update task
        cmd.Parameters.AddWithValue("@Action", "Update");
        cmd.Parameters.AddWithValue("@Id", Id);
        cmd.Parameters.AddWithValue("@Name", etxtName.Text.Trim());
        cmd.Parameters.AddWithValue("@Gender", eddlGender.SelectedItem.Text);
        cmd.Parameters.AddWithValue("@EMail", etxtEMail.Text.Trim());
        cmd.Parameters.AddWithValue("@CityId", eddlCity.SelectedItem.Value);
        cmd.ExecuteNonQuery();
        con.Close();
 
        gridEmployee.EditIndex = -1;
        BindGrid();
 
        lblMessage.Text = "Record updated successfully";
 
        btnAdd.Enabled = true;
        btnEdit.Visible = true;
        btnESave.Visible = false;
        btnDelete.Enabled = true;
 
    }
 
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        int rowCount = 0;
        con = new SqlConnection(MyConnString);
        cmd = new SqlCommand("proc_Employee", con);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
 
        foreach (GridViewRow gvrow in gridEmployee.Rows)
        {
            CheckBox chkRow = (CheckBox)gvrow.FindControl("chkRow");
            if (chkRow.Checked && chkRow != null)
            {
                //finding rowindex for delete
                editindex = gvrow.RowIndex;
 
                // retrieve Id from DataKeys to delete record
                int Id = Convert.ToInt32(gridEmployee.DataKeys[editindex].Values["Id"].ToString());
 
                // call the delete task
                cmd.Parameters.AddWithValue("@Action", "Delete");
                cmd.Parameters.AddWithValue("@Id", Id);
 
                cmd.ExecuteNonQuery();
                // clear parameter after every delete
                cmd.Parameters.Clear();
 
                rowCount++;
            }
        }
        con.Close();
 
        if (rowCount > 0)
        {
            lblMessage.Text = "Record deleted successfully";
            BindGrid();
        }
        else
        {
            lblMessage.Text = "Select record to Delete";
        }
    }
 
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        gridEmployee.EditIndex = -1;
        BindGrid();
 
        btnAdd.Enabled = true;
        btnEdit.Visible = true;
        btnESave.Visible = false;
        btnDelete.Enabled = true;           
    }
 
    protected void gridEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gridEmployee.PageIndex = e.NewPageIndex;
        BindGrid();
        lblMessage.Text = "";
    }
}