Friday, March 4, 2011

Delegates in C#.NET

Delegates in C# -

Delegates are used to Call non-member function of the Class/ Form. (functions of other class/ Form)
like e.g.

If we want to call load event of Form1 =>Form1_Load() event On closing of Form2 => Form2_Closing().


Coding =>

1. In Form1 Coding

public delegate voidForm1FormLoadHandler();

        public eventForm1FormLoadHandlerForm1FormLoad;

        public void OnFrm_BudgetDetailsFormLoad()
        {
            object s = null;
            EventArgs e = null;
           Form1_Load(s, e);
        }



In Form2 Coding


        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
                Form1 frm = (Form1)this.frm;
                Form1.Form1LoadHandler f = null;
                f += new Form1.Form1LoadHandler(frm.OnForm1Load);
                frm.OnForm1Load();
        }





Wednesday, March 2, 2011

C#.NEt - To Open any system application in C#.NET

// To open existing file of any type.
System.Diagnostics.Process.Start(string FileName);

// To open application, (and/or create new file).
System.Diagnostics.Process.Start("notepad",string FileName);

C#.NET - Export To Excel Contents of DataGridView Control


// Must include following libraries.

using System.IO;
using Microsoft.Office.Interop.Excel;

// Creating Object of System Application (e.g. Microsoft Excel)

private ApplicationClass xlApp = new ApplicationClass();

        private void createDataInExcel(DataSet ds)
        {
            Workbook xlWorkBook;
            Worksheet xlWorkSheet;
           
            object misValue = System.Reflection.Missing.Value;

            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            int i = 0;
            int j = 0;

       // set rows and columns of excel sheet = the rows and columns of datagridview control

            for (j = 1; j <= DataGirdViewControl.Columns.Count - 3; j++)
            {
                xlWorkSheet.Cells[i + 1, j + 1] = DataGirdViewControl.Columns[j].HeaderText.ToString();
            }

            for (i = 0; i <= DataGirdViewControl.RowCount  - 1; i++)
            {
                for (j = 1; j <= DataGirdViewControl.Columns.Count  - 3; j++)
                {
                    DataGridViewCell cell = DataGirdViewControl[j, i];
                    xlWorkSheet.Cells[i + 3, j + 1] = cell.Value;
                }
            }

        // Creating destination path, you can assign manually

            string strPath = System.Windows.Forms.Application.StartupPath;
            strPath = strPath.Replace(@"\bin\Debug", "");
            strPath = strPath + "\\Folder";

        // checking for exsting path, if exists it will replace it.
            if (!Directory.Exists(strPath))
                Directory.CreateDirectory(strPath);

            string strFileName = strPath + "\\Folder(" +  FileName  + ").xls";
           
            try
            {
        // To save Excel sheet.

                xlWorkBook.SaveAs(strFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();
            }
            catch (Exception oException)
            {
                MessageBox.Show("You can not access " + strFileName + ". This file might be already open.", "Budget Details", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

            MessageBox.Show("Excel file created , you can find the file \\Folder" + strFileName,"",MessageBoxButtons.OK,MessageBoxIcon.Information);
            xlWorkBook = null;
            xlWorkSheet = null;           
        }

private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

C#.NET - Rebind DataGridView Control after User Deleted Row

// Datagridview control is binded with DataSource.
// Deleting a row from DatagridView control and hence from DataBase,

private void DataGridView_KeyDown(View sender, KeyEventArgs e)
        {
            if (e.KeyValue == 46)
            {
                if (DataGridView.SelectedRows.Count > 0)
                {
                    if (MessageBox.Show("Are you sure you want to Delete  Record?", "Complaint Details", MessageBoxButtons.YesNo, MessageBoxIcon.Warning).ToString().ToLower() == "yes")
                    {
                        nIndex = DataGridView.SelectedRows[0].Index;
                        DeleteRow(nIndex);
                    }          
                }
            }
        }

// DeleteROw is user defined function, delete the record from database.

    private void DeleteRow(int nIndex)
        {
            int nDeleted;
            BusinessLayer oBusinessLayer = new BusinessLayer();

            nDeleted = oBusinessLayer.DeleteRecord("(" + DataGridView.Rows[nIndex].Cells["colID"].Value.ToString() + ")");
            if (nDeleted != 0)
            {
                MessageBox.Show("Record(s) can not be Deleted.", "Database", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("Record(s) Successfully Deleted.", "Databse", MessageBoxButtons.OK, MessageBoxIcon.Information);

        // Rebind the datasource with updated Databse
          
        Dtg_ComplaintDetails.DataSource = oDataTable;
                LoadDataGrid(oDataTable);            
            }
        }