How To send datagrid in function
I want to export datagrid information to excel file.My Problem is that i need to rewrite the same function in each windowsfrom that i want to export. Is it possible to sent the datagrid information to Main function??
the code is:
private void button2_Click(object sender, EventArgs e) { string name = textBox1.Text; Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); int i = 0; int j = 0; for (i = 0; i <= dgvCostumers.RowCount - 1; i++) { for (j = 0; j <= dgvCostumers.ColumnCount - 1; j++) { DataGridViewCell cell = dgvCostumers[j, i]; xlWorkSheet.Cells[i + 1, j + 1] = cell.Value; } } xlWorkBook.SaveAs(name + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); xlWorkBook.Close(true, misValue, misValue); xlApp.Quit(); releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp); MessageBox.Show("Excel file created , you can find the file c:\\my documents\\" + name + ".xls"); textBox1.Text = ""; textBox1.Visible = false; button1.Visible = true; label2.Visible = false; } } 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(); } }
Answers
How about something like
private void DataGridViewToExcel(string name, DataGridView dgv) { Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); int i = 0; int j = 0; for (i = 0; i <= dgv.RowCount - 1; i++) { for (j = 0; j <= dgv.ColumnCount - 1; j++) { DataGridViewCell cell = dgv[j, i]; xlWorkSheet.Cells[i + 1, j + 1] = cell.Value; } } xlWorkBook.SaveAs(name + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); xlWorkBook.Close(true, misValue, misValue); xlApp.Quit(); releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp); }
and then your button click code can change to something like
private void button2_Click(object sender, EventArgs e) { string name = textBox1.Text; DataGridViewToExcel(name, dgvCostumers); MessageBox.Show("Excel file created , you can find the file c:\\my documents\\" + name + ".xls"); textBox1.Text = ""; textBox1.Visible = false; button1.Visible = true; label2.Visible = false; } }