Tuesday 8 May 2012

download data in datagridview to word and Excel in window form application||Export data in data grid view to excel or word

Visual Studio->New project->Window Form Application

Step 1:
Drag and place DataGridView on the form and bind it with a datatable
  
Step 2:
Place two buttons and name it as Word And Excel
Add folderBrowserDialog control to Form

The Form[design] looks like this



Write the following code in form.cs:

Form.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using System.Drawing.Printing;
namespace updateaccess
{
    public partial class Form1 : Form
    {
        SqlConnection con = new SqlConnection("Data Source=Shailaja;Initial Catalog=Peers;User Id=sa;Password=123");
        public Form1()
        {
            InitializeComponent();
            SqlDataAdapter da = new SqlDataAdapter("Select * from emp", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            dataGridView1.DataSource = ds.Tables [0];
        }

        private void ToCsV(DataGridView dGV, string filename)
        {
            string stOutput = "";
            // Export titles:
            string sHeaders = "";

            for (int j = 0; j < dGV.Columns.Count; j++)
                sHeaders = sHeaders.ToString() + Convert.ToString(dGV.Columns[j].HeaderText) + "\t";
            stOutput += sHeaders + "\r\n";
            // Export data.
            for (int i = 0; i < dGV.RowCount - 1; i++)
            {
                string stLine = "";
                for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
                    stLine = stLine.ToString() + Convert.ToString(dGV.Rows[i].Cells[j].Value) + "\t";
                stOutput += stLine + "\r\n";
            }
            Encoding utf16 = Encoding.GetEncoding(1254);
            byte[] output = utf16.GetBytes(stOutput);
            FileStream fs = new FileStream(filename, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(output, 0, output.Length); //write the encoded file
            bw.Flush();
            bw.Close();
            fs.Close();
        }

      

        private void btnWord_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter = "Word Documents (*.doc)|*.doc";

            sfd.FileName = "time.doc";

            if (sfd.ShowDialog() == DialogResult.OK)
            {

                //ToCsV(dataGridView1, @"c:\export.xls");

                ToCsV(dataGridView1, sfd.FileName); // Here dataGridview1 is your grid view name

            }
        }

        private void btnExcel_Click(object sender, EventArgs e)
        {

           SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter = "Excel Documents (*.xls)|*.xls";

            sfd.FileName = "time.xls";

            if (sfd.ShowDialog() == DialogResult.OK)
            {

                //ToCsV(dataGridView1, @"c:\export.xls");

                ToCsV(dataGridView1, sfd.FileName); // Here dataGridview1 is your grid view name
}
            }
        }
       
        }



Run the application and view the output

Print Preview of Datagridview in Window Forms||Print Preview Dialog Example

How to see the preview of data grid view in Window forms

Visual Studio->New project->Window Form Application

Step 1:
Drag and place DataGridView on the form and bind it with a datatable

 Step 2:
Place one button and name it Preview, generate it's click event by double clicking on it We will use this event to see preview.

 Step 3:
Add Print Preview Dialog control to the Form

 Step 4:
Put Print Document control from toolbox under printing tab, Double click on it to generate it's PrintPage event.

Then The Form[design] looks like this




Write the code behind as follows:

Form.cs


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

namespace previewdatagridview
{
    public partial class Form1 : Form
    {
        SqlConnection con = new SqlConnection("Data Source=Shailaja;Initial Catalog=Peers;User Id=sa;Password=123");
        public Form1()
        {
            InitializeComponent();
            SqlDataAdapter da = new SqlDataAdapter("Select * from emp", con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            dataGridView1.DataSource = ds.Tables[0];
        }

        private void button1_Click(object sender, EventArgs e)
        {
            printPreviewDialog1.Document = printDocument1;
            printPreviewDialog1.PrintPreviewControl.Zoom = 1;
            printPreviewDialog1.ShowDialog();
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            Bitmap dataGridViewImage = new Bitmap(this.dataGridView1.Width, this.dataGridView1.Height);
            dataGridView1.DrawToBitmap(dataGridViewImage, new Rectangle(0, 0, this.dataGridView1.Width, this.dataGridView1.Height));
            e.Graphics.DrawImage(dataGridViewImage, 0, 0);
        }

      
    }
}


DEMO:





Tuesday 1 May 2012

Using Ms Access as a database for Inserting and retrieving values

Using Ms Access as a database for Storing and retrieving values

Step 1:
First create new database in Ms Access and name it as your wish.Create a table in Ms Access database




















Write a store procedure in Ms Access for inserting values
Select the Create tab in the toolbar at the top of the screen. Then click on the Query Design button under the Other group.





Next click on Queries tab in Show table and click close


 

 You will find a Query1 tab right click on it and select sqlview



 Write a query for inserting values in it and save it with the name Insertproc

Step 2:
New Project -> Window form application
Form[design].cs looks like this

Form1[design].cs:



Write the following code in Form1.cs

Form1.cs: 

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

namespace conctiontoaccess
{
    public partial class Form1 : Form
    {
       
      OleDbConnection con=new OleDbConnection (@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\dev6\Documents\Accessdb.accdb");
        public Form1()
        {
            InitializeComponent();
            bind();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OleDbCommand cmd = new OleDbCommand("insertproc",con);
                            
            cmd.Parameters.Add("@empname",txtname.Text);
            cmd.Parameters.Add("@cmpny", txtcmpny.Text);
            cmd.Parameters.Add("@loc", txtloc.Text);
           
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            int result=cmd.ExecuteNonQuery();
           
              if (result > 0)
            {
                MessageBox.Show("inserted successfully");
            }
            bind();
        }
        private void bind()
        {
            OleDbDataAdapter da = new OleDbDataAdapter("select * from test", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;
        }

    }
}


Demo:







Popup Window in Asp.net

Popup Window  Model
Step 1: Open visual studio->new website ->add new item-> web form

Add two link buttons from toolbox to web form  and add code to source page as given below:

Default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script>

        var winheight = 100
        var winsize = 100
        var x = 5
        function openwindow(thelocation) {
            temploc = thelocation
            if (!(window.resizeTo && document.all) && !(window.resizeTo && document.getElementById)) {
                window.open(thelocation)
                return
            }
            win2 = window.open("", "", "scrollbars")
            win2.moveTo(0, 0)
            win2.resizeTo(100, 100)
            go2()
        }
        function go2() {
            if (winheight >= screen.availHeight - 3)
                x = 0
            win2.resizeBy(5, x)
            winheight += 5
            winsize += 5
            if (winsize >= screen.width - 5) {
                win2.location = temploc
                winheight = 100
                winsize = 100
                x = 5
                return
            }
            setTimeout("go2()", 50)
        }
</script>

<script language="JavaScript">
    function expandingWindow(website) {
        var windowprops = 'width=100,height=100,scrollbars=yes,status=yes,resizable=yes'
        var heightspeed = 2; // vertical scrolling speed (higher = slower)
        var widthspeed = 7;  // horizontal scrolling speed (higher = slower)
        var leftdist = 10;    // distance to left edge of window
        var topdist = 10;     // distance to top edge of window

        if (window.resizeTo && navigator.userAgent.indexOf("Opera") == -1) {
            var winwidth = window.screen.availWidth - leftdist;
            var winheight = window.screen.availHeight - topdist;
            var sizer = window.open("", "", "left=" + leftdist + ",top=" + topdist + "," + windowprops);
            for (sizeheight = 1; sizeheight < winheight; sizeheight += heightspeed)
                sizer.resizeTo("1", sizeheight);
            for (sizewidth = 1; sizewidth < winwidth; sizewidth += widthspeed)
                sizer.resizeTo(sizewidth, sizeheight);
            sizer.location = website;
        }
        else
            window.open(website, 'mywindow');
    }

</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <a href="javascript:openwindow('http://www.AryabhattaSolution.com')">link1</a>
    <br />
    <a href="#" onClick="expandingWindow('http://www.c-sharpcorner.com');return false">link2</a>
    </div>
    </form>
</body>
</html>

Run the application 
Click link1 to see Horizontal window popup
Click link2 to see Vertical Window popup