Export From DataGridView To Excel-Sheet in C#

using Excel = Microsoft.Office.Interop.Excel;  // Add Refference of Microsoft.Office.Interop.Excel.dll

// The Data that would be in the DataGridView will be Export to Excel Sheet. By
private void ExportToExcel () //Here ‘gridview_newadmission’ is the Name of the DataGridView
{

try
{

Microsoft.Office.Interop.Excel.Application xlApp; Microsoft.Office.Interop.Excel.Workbook xlWorkBook; Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value;

xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

for (int c = 0; c < gridview_newadmission.ColumnCount; c++)
{

xlWorkSheet.Cells[1, c + 1] = gridview_newadmission.Rows[0].Cells[c].OwningColumn.Name.ToString();
xlWorkSheet.Cells.ColumnWidth = 15;

}

for (int r = 0; r < gridview_newadmission.RowCount; r++)
{

for (int c = 0; c < gridview_newadmission.ColumnCount; c++)
{

DataGridViewCell cell = gridview_newadmission[c, r];
xlWorkSheet.Cells[r + 2, c + 1] = cell.Value;

}

}

FolderBrowserDialog SelectTarget = new FolderBrowserDialog();
SelectTarget.ShowDialog();
string path = SelectTarget.SelectedPath;
if (path != “”)
{

xlWorkBook.SaveAs(path + “\\myData.xls”, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

}
statusMessage.ForeColor = Color.Black;
statusMessage.Text = “Data Saved to ” + path;

 }
catch (Exception)
{}

}

Easy Shortcut Keys in Windows Form C#

Protected override bool ProcessCmdKey(ref Message msg, Keys keyData) //Simple Put this code in Form and Assign the Keys and Line   of Code that must be executed on that key press.
{

if (keyData == (Keys.Control | Keys.X)) //On Pressing Ctrl + X the Event is Detected.
{

MessageBox.Show(“You Have Press Ctrl + X?”);
this.Close();
return true;

}

return base.ProcessCmdKey(ref msg, keyData);

}

Get Current Financial Year in C#

public static string GetCurrentFinancialYear()
{

int CurrentYear = DateTime.Today.Year;
int PreviousYear = DateTime.Today.Year – 1;
int NextYear = DateTime.Today.Year + 1;
string PreYear = PreviousYear.ToString();
string NexYear = NextYear.ToString();
string CurYear = CurrentYear.ToString();
string FinYear = null;

if (DateTime.Today.Month > 3)

FinYear = CurYear + “-” + NexYear;

else

FinYear = PreYear + “-” + CurYear;

return FinYear.Trim();

}