Friday, 26 October 2012

Delegate Part 2

In Delegate Part 1 :-I have explained how to declare a delegate and create an instance of it and use it. Now i am going to explain Multicast Delegate.

We can also create a delegate which can point to multiple functions and methods. If we invoke such delegate it will invoke all the methods and functions associated with the same one after another sequentially.In order to add multiple methods and function we need to use ‘+=’ symbols. Now if we invoke the delegate it will invoke ‘Method1’ first and then ‘Method2’. Invocation happen in the same sequence as the attachment is done.

// Associate method1
mydelegate += Method1;
// Associate Method2
mydelegate += Method2;
// Invoke the Method1 and Method2 sequentially
mydelegate.Invoke();
 
 
 
..... 

Thursday, 4 October 2012

How to Export Data Of DataGridview To Excel using C# Windows Appllication

Namespaces

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 MySql.Data.MySqlClient;
using System.Configuration;
using System.IO;

Function For  Exporting To Excel

private void ToCsV(DataGridView data, string file)
        {
            string stOutput = "";
            string sHeaders = "";

            for (int j = 0; j < data.Columns.Count; j++)
                sHeaders = sHeaders.ToString() + Convert.ToString(dataColumns[j].HeaderText) + "\t";
            stOutput += sHeaders + "\r\n";
         
            for (int i = 0; i < dataRowCount - 1; i++)
            {
                string stLine = "";
                for (int j = 0; j < data.Rows[i].Cells.Count; j++)
                    stLine = stLine.ToString() + Convert.ToString(data.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);
            bw.Flush();
            bw.Close();
            fs.Close();
        }

Code For Button On Export To Excel

            SaveFileDialog sfd = new SaveFileDialog();

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

            sfd.FileName = "export.xls";

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

                ToCsV(dataGridView1, sfd.FileName);
            }