Showing posts with label Winform Examples. Show all posts
Showing posts with label Winform Examples. Show all posts

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:







TextBox Colored Border

How to change Textbox border color when user enters in to it
Step 1:
Open visual studio ->New project-> Window form application
Add textbox from toolbox to the form and write the  following code

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;

namespace textboxcolorborder
{
    public partial class Form1 : Form
    {
        bool focus = false;

        public Form1()
        {
            InitializeComponent();
           

        }
      
        private void Form1_Load(object sender, EventArgs e)
        {
          
        }

        private void textBox1_Enter(object sender, EventArgs e)
        {
            focus = true;
            this.Refresh();

        }

        private void textBox1_Leave(object sender, EventArgs e)
        {
            focus = false;
            this.Refresh();

        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            if (focus)
            {
                textBox1.BorderStyle = BorderStyle.None;
                Pen p = new Pen(Color.Red);
                Graphics g = e.Graphics;
                int variance = 3;
                g.DrawRectangle(p, new Rectangle(textBox1.Location.X - variance, textBox1.Location.Y - variance, textBox1.Width + variance, textBox1.Height + variance));
            }
            else
            {
                textBox1.BorderStyle = BorderStyle.FixedSingle;
            }

        }

       
    }
}

 
Demo: