Create a PDF file using Crystal Report in C#

Crystal Report’s “ExportToStream” function can export a pre designed report into various file format and “ExportToDisk” function can export the entire formated data into a specified file. In this article we’ll use the “ExportToDisk” function, which allows us to convert the report into a PDF file and save it in a folder. The file can then be emailed or printed.

Create PDF using Crystal report

Note: We assume that you have read our article on How to create Crystal Report in Asp.Net?

Please read the above article first, since in this article we will use the same file and database format for the demo.

Once you have created a project with the Crystal report, just write another function (CreatePDF) which will create a PDF file using the data extracted from the database.

 

Also add few crystal report references to your project. To add references, click “Website” from the top menu select “Add Reference…” menu. In the “.Net” tab search for,

1) CrystalDecisions.CrystalReports.Engine
2) CrystalDecisions.Shared

 

using System;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;                  // FOR DataSet().
using CrystalDecisions.Shared;      // FOR ExportFormatType.

public partial class _Default : System.Web.UI.Page 
{
    // CONNECTION PROPERTIES.
    SqlConnection myConn = default(SqlConnection);
    SqlCommand sqComm = default(SqlCommand);

    public CrystalDecisions.CrystalReports.Engine.ReportDocument Report = 
        new CrystalDecisions.CrystalReports.Engine.ReportDocument();

    protected void btPDF_Click(object sender, EventArgs e)
    {
        if (setConn())
        {
            string sQuery = "SELECT *FROM dbo.Employee";
            CreatePDF(sQuery, "Employee.rpt", "Employee");
        }
    }

    private bool CreatePDF(string sQuery, string rptFileName, string sTableName)
    {
        System.Data.SqlClient.SqlDataAdapter objDataAdapter = 
            new System.Data.SqlClient.SqlDataAdapter(sQuery, myConn);

        DataSet objDataSet = new DataSet()>;
        objDataAdapter.SelectCommand.CommandTimeout = 100;
        objDataAdapter.Fill(objDataSet, sTableName);

        Report.Load(Server.MapPath("report\\") + rptFileName);
        Report.SetDataSource(objDataSet);                  // SET REPORT DATA SOURCE.

        // FINALLY, CREATE THE PDF FILE USING EMPLOYEE DETAILS.
        Report.ExportToDisk(ExportFormatType.PortableDocFormat, 
            Server.MapPath("Crystal-to-PDF\\EmployeeDetails.pdf"));

        return true;
   }

    private bool setConn()
    {
        // SET DATABASE CONNECTION.
        try
        {
            myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DNA_DB"].ConnectionString);
            myConn.Open();            sqComm = new SqlCommand();
            sqComm.Connection = myConn;
        }
        catch (Exception ex) { return false; }
        return true;
    }
}

Our function “CreatePDF” is called from the button click event and it takes 3 parameters.

1) sQuery: The “Sql” query that will fetch the details from the “Employee” table.

2) rtpFileName: The “Crystal Report” file which we have designed earlier. This is the file which will be converted into “PDF”.

3) sTableName: The name of the “DataSet” which holds the table data and will be used to design the report.

How to create composite custom control and add them into toolbox

Composite control is very important functionality provided by the Microsoft.NET.Using custom control we can make windows forms application very easily. In Custom control application we can combine multiple controls according to our requirements.We can easily merge this custom control in any windows application.

Step 1:- First open your visual studio –> File –>New–>Project–>Select windows Forms control Library–>OK–>Now Drag and Drop Label, TextBox and Button control as shown below:-

login form

Step 2:- Now Double click on Login Button–> and write the following codes:-

usingSystem;
usingSystem.ComponentModel;
usingSystem.Text;
usingSystem.Windows.Forms;
namespaceWindowsFormsControlLibrary1
{
    publicpartialclasscustomcontrol : UserControl
    {
        publicdelegatevoiddel();
        publiceventdel checkdetails;
        publicstringpid
        {
            set
            {
                textBox1.Text = value;
            }
            get
            {
                returntextBox1.Text;
            }
        }
        publicstringpassword
        {
            set
            {
                textBox2.Text = value;
            }
            get
            {
                returntextBox2.Text;
            }
        }
        publiccustomcontrol()
        {
            InitializeComponent();
        }
        privatevoidbutton1_Click(objectsender, EventArgs e)
        {
            if(textBox1.Text == ""&& textBox2.Text == "")
            {
                MessageBox.Show("please enter details");
            }
            elseif(textBox1.Text == "")
            {
                MessageBox.Show("please enter id");
            }
            elseif(textBox2.Text == "")
            {
                MessageBox.Show("please enter password");
            }
            else
            {
                if(checkdetails != null)
                {
                    checkdetails();
                }
                else
                {
                    MessageBox.Show("enter correct dtails");
                }
            }
        }
    }
}
Step 3:-Now Run the Application(press F5) –> and click on Load Button –> copy URL Path,which is as shown below:-

copy url
Step 4:– Now open your visual studio –> File–> New–>project–>Windows forms Application –>OK–>Now open Toolbox–>Right click on Toolbox –>click choose items as shown below:

choose items
Step 5:– Now click browse –> Paste the Url that you have copied before(otherwise Run First Application and get Url again)–>click on Arrow Button –> Select dll file as shown below–>Now click on  open Button.

select dll

Step 6:-Now open your Toolbox and Drag & Drop composite custom control on the Form as shown below:-

Toolbox

Step 7:– Now Double click on Form and write the following codes on the Form Load as given below.

usingSystem;
usingSystem.ComponentModel;
usingSystem.Text;
usingSystem.Windows.Forms;
namespacecomposite_application
{
    publicpartialclassForm1 : Form
    {
        publicForm1()
        {
            InitializeComponent();
        }
        privatevoidForm1_Load(objectsender, EventArgs e)
        {
            customcontrol1.checkdetails += newWindowsFormsControlLibrary1.customcontrol.del(customcontrol1_checkdetails);
        }
        voidcustomcontrol1_checkdetails()
        {
            if(customcontrol1.pid == "user"&& customcontrol1.password == "pass")
            {
          MessageBox.Show("welcome to https://codeworldtechnology.wordpress.com/ share it if possible");
            }
            else
            {
                MessageBox.Show("invalid user");
            }
        }
    }
}
Step 8:– Run the Application(press F5).There are some credentials which i have set in dll file which are given below:-

  • If you leave both Textbox field blank then it will give error”Please enter the password”.
  • If you leave only password field  blank then then it will give error “please enter password”.
  • If you leave only User Name Field blank then it will error “please enter the id”.
  • If you fill both fill both Field correctly then it will give  Message “Welcome to http://msdotnet.co.in ,share it if possible”.
success
  • If you enter both field wrong then it will give error “Invalid user”.

AccessKey property of TextBox in .Net

Using the AccessKey property you can directly navigate to the control Or you can say directly focus to the control. Accesskey property is basically used for when you have a large page content and you want to directly navigate to particular control on that time you should use AccessKey property. Another one example is , suppose your mouse are not working properly on that time AccessKey will working for focusing control.

<%@ Page Language=”C#” %>
<!DOCTYPE html>
<script runat=”server”>
</script>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
    <title></title>
    <style type=”text/css”>
        .auto-style1 {
  text-decoration: underline;
        }
    </style>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
 
        <span>U</span>serName :

        <asp:TextBox ID=”TextBox1″ runat=”server” AccessKey=”U” Width=”159px”></asp:TextBox>
<br />
        <span>P</span>assWord :&nbsp;
        <asp:TextBox ID=”TextBox2″ runat=”server” AccessKey=”P” Width=”157px”></asp:TextBox>
        <br />
        <asp:Button ID=”Button1″ runat=”server” Text=”Submit” />
 
    </div>
    </form>
</body>
</html>


Output

AccessKey Property of TextBox in ASP.NET

 

AccessKey Property of TextBox in ASP.NET

 

 

Passing Values from DataGridView between Different Forms.

Sometimes we need to transfer all the rows and columns of a DataGridView from one form to another. In this article I will transfer all the binded data of first form’s grid view and bind them to second form’s grid view.

Create two forms, Form1 is parent form and Form2 is child form. Bind data to DataGridView as below:

1

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace GridView_Examples_WindowsForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = true;
  }

        private void button1_Click(object sender, EventArgs e)
        {
            BindGrid();
        }

        private void BindGrid()
        {
            List empList = new List();
            empList.Add(new Employee() { EmployeeName = “Sunil”, EmployeeID = “Emp-s1”, Department = “Developement”, Address = “Jaipur” });
    empList.Add(new Employee() { EmployeeName = “Maya”, EmployeeID = “Emp-m2”, Department = “Developement”, Address = “Jaipur” });
            empList.Add(new Employee() { EmployeeName = “Sneha”, EmployeeID = “Emp-s3”, Department = “QA”, Address = “Calcutta” });
            empList.Add(new Employee() { EmployeeName = “Karuna”, EmployeeID = “Emp-k4”, Department = “HR”, Address = “Jaipur” });
            empList.Add(new Employee() { EmployeeName = “Poonam”, EmployeeID = “Emp-p5”, Department = “Production Support”, Address = “Mumbai” });
            empList.Add(new Employee() { EmployeeName = “Varsha”, EmployeeID = “Emp-v6”, Department = “Marketing”, Address = “Delhi” });
            dataGridView1.DataSource = empList;
        }

private void button2_Click(object sender, EventArgs e)
        {
            List<Employee> empList = dataGridView1.DataSource as List<Employee>;
            new Form2(empList).ShowDialog();
        }
    }
    public class Employee
    {
        public string EmployeeName { get; set; }
        public string EmployeeID { get; set; }
        public string Department { get; set; }
        public string Address { get; set; }
    }
}

Note: In the above code you can see that, inside click event of button2 I am passing List object to constructor of Form2.

Form2:

1

using System.Collections.Generic;
using System.Windows.Forms;
namespace GridView_Examples_WindowsForm
{
    public partial class Form2 : Form
    {
        public Form2(List empList)
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = true;
            dataGridView1.DataSource = empList;
        }
    }
}

 

Text box validation using C#.

Masked textbox supports a declarative syntax for accepting or rejecting user input. To validate user input we have to use some additional mechanism like JavaScript/jQuery or server side validation. But we can do the same without using any of these mechanism. To perform this job we can use “KeyPress” event of TextBox.

Textbox’s Key Press event occurs when the control has focus and user press and releases a key. It has following format that is in C# language:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
}

 

The parameter e provides the data for this event which is of type KeyPressEventArgs. Char class has some in-built functions for checking the pressed and released key by user.

char.IsDigit(): whether the character is decimal digit or not.
char.IsLetter(): whether the character is a letter.
Char.IsLetterOrDigit(): whether the character is letter or digit.

To restrict the user from entering the digit in textbox:

if (char.IsDigit(e.KeyChar))
e.Handled = true;

 

Here e.Handled will tell the debugger that I have handled this event. We can use desired method to prevent specified type of key by the user.

To restrict both the letter and digit to be inputted by the user in c# language:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsLetterOrDigit(e.KeyChar) || char.IsDigit(e.KeyChar))
e.Handled = true;
}

 

 

Programe to find Prime number in between range in C#.

Hi All, this is very simple program but I was getting bored so I am posting it 😛

We have two numbers n1 and n2. And we need to find all the prime numbers in between these two.

using System;

namespace ConsoleApplication
{
    class Odd_Even_Numbers
    {
        public static void Main()
        {
            int n1, n2;
            string nPrime = string.Empty;
            Console.WriteLine(“enter first number: “);
            n1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(“enter second number: “);
            n2 = Convert.ToInt32(Console.ReadLine());
    FindPrimeNumber(n1, n2, nPrime);
        }

        private static void FindPrimeNumber(int n1, int n2, string nPrime)
        {
            bool flag = true;
            for (; n1 <= n2; ++n1)
            {
                flag = true;
                for (int i = 2; i <= n1 / 2; ++i)
                {
                    if (n1 % i == 0)
     {
                        flag = false;
                        break;
                    }
                }
                if (flag)
                {
                    nPrime += n1.ToString() + “, “;
                }
            }
            Console.WriteLine(“Prime numbers are: ” + nPrime);
            Console.ReadLine();
        }
    }
}

 

 

 

Encapsulation in OOPs.

Encapsulation is the ability of an object oriented language (C# in this context) to hide unnecessary implementation details from the object user. Encapsulation makes coding simpler and helps to preserve data integrity.

According to the concept of encapsulation, an object’s internal data should not be directly accessible from an object instance. Members of a class that represent an object’s state should not be marked as public. The state of an object should only be altered indirectly by using public members. C# prefers properties to encapsulate data.

Ex.

class ABC
{
// private data members
private int roll;
private int class;
private string name;
// public properties
public int Roll
{
get { return roll; }
set { roll = value; }
}
public int Class
{
get { return class; }
set { class = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
// constructor
public ABC()
{
// values are assigned to data members via properties
Roll = 10;
Class = 9;
Name = “Sunil Kumar Meena”;
}
}

Polymorphism in OOPs.

Polymorphism is the ability of an object oriented language (C# in this context) to allow a base class to define a set of members (formally termed the polymorphic interface) that are available to all descendents. A class’s polymorphic interface is constructed using any number of virtual or abstract members.
A virtual member is a member in a base class that defines a default implementation that may be changed (overridden) by a derived class.
In contrast, an abstract method is a member in a base class that does not provide a default implementation, but does provide a signature. When a class derives from a base class defining an abstract method, it must be overridden by a derived type.
In either case (virtual or abstract), when derived types override the members defined by a base class, they are essentially redefining how they respond to the same request.
Method Overriding – Method Overriding is a process in which a derived class can define its own version of a method, which was originally defined by its base class.
Virtual Keyword – The virtual keyword indicates that the base class wants to define a method which may be (but does not have to be) overridden by a derived class. A virtual method provides a default implementation that all derived types automatically inherit. If a child class so chooses, it may override the method but does not have to.
Note: Subclasses are never required to override virtual methods.
Override Keyword – The override keyword is used by a derived class to to change the implementation details of a virtual method (defined in the base class). Each overridden method is free to leverage the default behavior of the parent class using the base keyword.
Sealed Keyword – The sealed keyword is basically applied to classes to prevent other types from extending its behavior via inheritance.
It can also be applied to virtual methods to prevent derived types from overriding those methods. Ex.
public override sealed void GiveBonus(float amount)
{
}
Any effort to override the above sealed method in the derived class will generate compile time error.
Abstract Classes – The abstract keyword can be used in the class definition to prevent direct creation of an instance of the class. Although abstract classes cannot be created directly, it is still assembled in memory when derived classes are created. Thus, it is perfectly fine for abstract classes to define any number of constructors that are called indirectly when derived classes are allocated.
An abstract class can define any number of abstract members (members that does not supply a default implementation, but must be accounted for by each derived class).
The polymorphic interface of an abstract base class simply refers to its set of virtual and abstract methods. Methods marked with abstract are pure protocol. They simply define the name, return type (if any), and parameter set (if required).
If you do not override an abstract method (of the base abstract class) in the derived class, the derived class will also be considered abstract, and would have to be marked abstract with the abstract keyword.
Although it is not possible to directly create an instance of an abstract base class, you can freely store references to any subclass with an abstract base variable.

Multiple Main methods in a C# programe

In this article I shall explain how to use multiple Main methods in a program. To do so we need to make some changes in settings.

using System;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                Console.WriteLine("VALUE IS=" + args[i]);
 
            }
            Console.ReadLine();
        }
    }
    class student
    {
        static void Main(string[] args)
        {
            if (args[0] == "user" && args[1] == "pass")
            {
                Console.WriteLine("welcome user");
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("invalid  user");
                Console.ReadLine();
            }
        }
 
    }
    }

Description:- we  can use more than one main method in the program,But compiler is not know that which main method take as an entry point. so we have to set an entry point from the Startup Object in the Framework.
Here we have used two main method in above program, now I am going to execute them one by one
There are some steps to Run main method in above program.
Step1:- First open your visual studio->go File->New project->Select Console Application>click OK->copy the above code and paste the program.cs file.
see it:-

1

Step2:- Open Solution Explorer window-> Right click on Your project->click properties .
see it:-

2

After click on properties of main method program, window will be opened.it is like this:-

3

Step3:- Click the Debug -> Pass the value(which you want) in Command line arguments.
see it:- here i have two value “user” ,”pass”.

Step4:- Now click on Application->go Startup object->select class which main method you want to execute.
see it:-here i have selected student class ,so student class main method will be executed.

5

 

Now run your program.

 

Source: http://www.msdotnet.co.in/2012/06/how-to-use-multiple-main-method-in-c.html

 

Generate XML from C#.

Hi all, in this post I’ll explain how to generate XML file using C# classes. Suppose we want to generate a XML file for our DataSet or DataTable,  what we generally do, we use “GetXml()” method of DataSet to generate XML. But in this approach we do not have one single customization option like I want nested tags, attributes etc. So GetXml() does not help us always.

Here is my approach to generate XML with full of customization features. You are free to make any changes.  The following is my data:

[EmpId]    [EmpName]             [EmpSalary]    [Status]    [Deduction]        [Notes]
1                   Sunil Kumar            60000.00        1                  5500.00              hi this is sunil
2                   Sanjeev Kumar      50000.00        1                  6000.00              NULL
3                   Poonam Sharma   35000.00        0                  2600.00              hi this is poonam and my id is 3
4                   Maya                          50000.00       1                    4000.00            hi this is maya and my id is 4

I want EmpName, EmpSalary, Deduction and Notes as element tags and EmpId as attribute of EmpName and Status(1: Active, 0:Inactive )  as attribute of Notes.

DataTable dt = DLL.GetEmployeeInfo(0);
        if (dt != null && dt.Rows.Count > 0)
        {
            if (System.IO.File.Exists(Server.MapPath(“~/UserData/DatatableXML.xml”)))
            {
                System.IO.File.Delete(Server.MapPath(“~/UserData/DatatableXML.xml”));
            }
            using (XmlWriter write = XmlWriter.Create(Server.MapPath(“~/UserData/DatatableXML.xml”)))
            {
                write.WriteStartDocument();
                write.WriteStartElement(“Employee”);
                foreach (DataRow row in dt.Rows)
                {
                    write.WriteStartElement(“EmployeeInfo”);

                    write.WriteStartElement(“Name”);
                    write.WriteAttributeString(“ID”, Convert.ToString(row[“EmpId”]));
                    write.WriteString(Convert.ToString(row[“EmpName”]));
                    write.WriteEndElement();

                    write.WriteStartElement(“Salary”);
                    write.WriteString(Convert.ToString(row[“EmpSalary”]));
                    write.WriteEndElement();

                    write.WriteStartElement(“Deduction”);
                    write.WriteString(Convert.ToString(row[“Deduction”]));
                    write.WriteEndElement();

                    write.WriteStartElement(“Notes”);
                    write.WriteAttributeString(“Status”, Convert.ToString(row[“Status”]) == “1” ? “Active” : “In-Active”);
                    write.WriteString(Convert.ToString(row[“Notes”]));
                    write.WriteEndElement();
                    write.WriteEndElement();
                }
                write.WriteEndElement();
                write.WriteEndDocument();
            }
        }
        System.Diagnostics.Process.Start(Server.MapPath(“~/UserData/DatatableXML.xml”));

1