C# Excel to .TXT - c#

I'm starting to play with C# / .NET. My work background is Python.
Im having difficulty solving the conversion from Excel to TXT.
What i need the txt file to look like is:
ROW1COLUM1;ROW1COLUM2;ROW1COLUM3 //Note the lack of ";" on line break.
ROW2COLUM1;ROW2COLUM2;ROW3COLUM3
I am trying to at least save 1 cell in the txt but i cant. Code below:
private void button1_Click(object sender, EventArgs e) // Go
{
File.Create(#"C: \Users\AG\.PyCharmCE2017.2\config\scratches\testnet.txt").Close();
TextWriter tw = new StreamWriter(#"C: \Users\AG\.PyCharmCE2017.2\config\scratches\testnet.txt");
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fileName);
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
string[] dataRow = new string[15]; //fixed number for now
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
dataRow[j - 1] = xlWorksheet.Cells[i, j].Value.ToString();
}
tw.WriteLine(dataRow[1]); // Just checking if i can write something
}
MessageBox.Show("OK");
tw.Close();
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
I also need to save the .txt file as unicode, in case that matters.
This is probably very basic, i just couldn't find an answer.
Thanks
EDIT:
I managed to make it work. I also added a backgroundWorker.
The problem i have is performance. Can someone point me in the right direction?
Code:
if (goNoGo)
{
string sourceDirectory = Path.GetDirectoryName(fileName);
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
File.Create(sourceDirectory + filenameWithoutExtension).Close();
TextWriter tw = new StreamWriter(sourceDirectory + "\\" + filenameWithoutExtension + ".txt", true, Encoding.Unicode);
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fileName);
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
string dataRow = "";
int z = 1;
if (checkBox1.Checked)
{
z = 2;
}
int cont = 0;
for (float i = z; i <= rowCount; i++)
{
if (i % 250 == 0) // every 250 rows, check BW updates
{
cont = ((int)((i / rowCount) * 100));
backgroundWorker1.ReportProgress(cont);
//MessageBox.Show(cont.ToString());
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
}
for (int j = 1; j <= colCount; j++)
{
try
{
if (j == 1)
{
dataRow = xlWorksheet.Cells[i, j].Value.ToString();
}
else
{
dataRow += ";";
dataRow += xlWorksheet.Cells[i, j].Value.ToString();
}
}
catch (Exception ex) // catches empty cells
{
if (j == 1)
{
dataRpw = "";
}
else
{
dataRow += ";";
dataRow += "";
}
continue;
}
}
tw.WriteLine(dataRow);
}
tw.Close();
//cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.ReleaseComObject(xlRange);
Marshal.ReleaseComObject(xlWorksheet);
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
backgroundWorker1.ReportProgress(100);
}
else if (extensionWrong)
{
MessageBox.Show("File must be .xls");
}
else
{
MessageBox.Show("Load a file");
}
A 30k row file can take up to an hour. Any ideas?

Please try this and feedback.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Excel;
namespace test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataSet result = new DataSet();
private void button1_Click(object sender, EventArgs e)
{
string fileName = "";
fileName = textBox3.Text;
if (fileName == "")
{
MessageBox.Show("Enter Valid file name");
return;
}
converToCSV(comboBox1.SelectedIndex);
}
private void button2_Click(object sender, EventArgs e)
{
string Chosen_File = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Chosen_File = openFileDialog1.FileName;
}
if (Chosen_File == String.Empty)
{
return;
}
textBox1.Text = Chosen_File;
getExcelData(textBox1.Text);
}
private void button3_Click(object sender, EventArgs e)
{
DialogResult result = this.folderBrowserDialog1.ShowDialog();
string foldername = "";
if (result == DialogResult.OK)
{
foldername = this.folderBrowserDialog1.SelectedPath;
}
textBox2.Text = foldername;
}
private void getExcelData(string file)
{
if (file.EndsWith(".xlsx"))
{
// Reading from a binary Excel file (format; *.xlsx)
FileStream stream = File.Open(file, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
result = excelReader.AsDataSet();
excelReader.Close();
}
if (file.EndsWith(".xls"))
{
// Reading from a binary Excel file ('97-2003 format; *.xls)
FileStream stream = File.Open(file, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
result = excelReader.AsDataSet();
excelReader.Close();
}
List<string> items = new List<string>();
for (int i = 0; i < result.Tables.Count; i++)
items.Add(result.Tables[i].TableName.ToString());
comboBox1.DataSource = items;
}
private void converToCSV(int ind)
{
// sheets in excel file becomes tables in dataset
//result.Tables[0].TableName.ToString(); // to get sheet name (table name)
string a = "";
int row_no = 0;
while (row_no < result.Tables[ind].Rows.Count)
{
for (int i = 0; i < result.Tables[ind].Columns.Count; i++)
{
a += result.Tables[ind].Rows[row_no][i].ToString() + ",";
}
row_no++;
a += "\n";
}
string output = textBox2.Text + "\\" + textBox3.Text + ".csv";
StreamWriter csv = new StreamWriter(#output, false);
csv.Write(a);
csv.Close();
MessageBox.Show("File converted succussfully");
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
comboBox1.DataSource = null;
return;
}
}
}

Related

Save datagrid information to text file shows an empty file

I have code that allows you to save datagrid information in visual studio into a text file but the datagrid is filled out and it just shows nothing in the text file
Code:
private void button3_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = "untitled.txt";
sfd.DefaultExt = "txt";
sfd.Filter = "txt files (*.text) |*.txt*";
if (sfd.ShowDialog() == DialogResult.OK)
{
Stream fileStream = sfd.OpenFile();
StreamWriter sw = new StreamWriter(fileStream);
for(int i = 0; i < dataGridView1.Rows.Count - 1; i++) //rows
{
for (int j = 0; j < dataGridView1.Columns.Count; j++) // columns
{
sw.Write("\t", dataGridView1.Rows[i].Cells[j].Value.ToString() + "\t" + "|");
}
sw.WriteLine("");
}
sw.Close();
fileStream.Close();
}
}
In my small tests, it appears the “\t” is getting misinterpreted. Fortunately, a simple fix is to simply make a Tab string and use it like…
string tab = "\t";
Then…
sw.Write( tab + dataGridView1.Rows[i].Cells[j].Value.ToString() + tab + "|");
In addition, it is a good idea to implement using statements to ensure the resources get closed and disposed of properly. Something like…
private void button2_Click(object sender, EventArgs e) {
using (SaveFileDialog sfd = new SaveFileDialog()) {
sfd.FileName = "untitled.txt";
sfd.DefaultExt = "txt";
sfd.Filter = "txt files (*.text) |*.txt*";
string tab = "\t";
if (sfd.ShowDialog() == DialogResult.OK) {
using (Stream fileStream = sfd.OpenFile()) {
using (StreamWriter sw = new StreamWriter(fileStream)) {
for (int i = 0; i < dataGridView1.Rows.Count; i++) {
if (!dataGridView1.Rows[i].IsNewRow) {
for (int j = 0; j < dataGridView1.Columns.Count; j++) {
sw.Write(tab + dataGridView1.Rows[i].Cells[j].Value.ToString());
if (j < dataGridView1.Columns.Count - 1) {
sw.Write(tab + "|");
}
}
sw.WriteLine("");
}
}
//sw.Close();
//fileStream.Close();
}
}
}
}
}
Here is an option
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace YourNamespaceGoesHere
{
public static class DataGridViewExtensions
{
public static void ExportRows(this DataGridView sender, string fileName, string defaultNullValue = "(empty)")
{
File.WriteAllLines(fileName, (sender.Rows.Cast<DataGridViewRow>()
.Where(row => !row.IsNewRow)
.Select(row => new {
row,
rowItem = string.Join(",", Array.ConvertAll(row.Cells.Cast<DataGridViewCell>()
.ToArray(), c => ((c.Value == null) ? defaultNullValue : c.Value.ToString())))
})
.Select(#row => #row.rowItem)));
}
}
}
Usage (replace the file name from your SaveFileDialog)
private void ExportButton_Click(object sender, EventArgs e)
{
dataGridView1.ExportRows("data1.txt");
}

C# writing into excel files by using XLWorkbook

Sample Excel to be imported:
Data
First
Second
Third
My code at the moment:
private void button5_Click(object sender, EventArgs e)
{
OpenFileDialog ope = new OpenFileDialog();
ope.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
if (ope.ShowDialog() == DialogResult.Cancel)
return;
FileStream stream = new FileStream(ope.FileName, FileMode.Open);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet ds = excelReader.AsDataSet();
int counter = 1;
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
if (table.Rows.IndexOf(dr) != 0)
{
string SINs = Convert.ToString(dr[1]);
textBox7.Text = SINs;
Console.WriteLine(SINs);
Console.WriteLine(counter);
var wb = new XLWorkbook();
var worksheet = wb.Worksheets.Add("SINS");
for (int i=1; i<counter; i++)
{
worksheet.Cell(i, 1).Value = SINs;
}
wb.SaveAs("C:\\Users\\WYCHIN\\Desktop\\YONG_TEMP\\DHL API\\Sins.xlsx");
counter++;
}
}
}
}
What i wanted to be imported into the Sins.xlsx without header:
No Header
First
Second
Third
What i get from my code above:
No header
Third
Third
Third
Did i messed up my logic here?
Thanks in advance!
You should take lines
var wb = new XLWorkbook();
var worksheet = wb.Worksheets.Add("SINS");
and
wb.SaveAs("C:\\Users\\WYCHIN\\Desktop\\YONG_TEMP\\DHL API\\Sins.xlsx");
out of the loop.
For each row you're creating new worksheet and saving xlsx file.
I cannot test it (I don't have your DataTables), but you should try something like this:
private void button5_Click(object sender, EventArgs e)
{
OpenFileDialog ope = new OpenFileDialog();
ope.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
if (ope.ShowDialog() == DialogResult.Cancel)
return;
FileStream stream = new FileStream(ope.FileName, FileMode.Open);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet ds = excelReader.AsDataSet();
int counter = 1;
var wb = new XLWorkbook();
var worksheet = wb.Worksheets.Add("SINS");
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
string SINs = Convert.ToString(dr[1]);
textBox7.Text = SINs;
Console.WriteLine(SINs);
Console.WriteLine(counter);
for (int i=1; i<counter; i++)
{
worksheet.Cell(i, 1).Value = SINs;
}
counter++;
}
}
wb.SaveAs("C:\\Users\\WYCHIN\\Desktop\\YONG_TEMP\\DHL API\\Sins.xlsx");
}
EDIT: removed unnecessary checking for row index.
Thank you for your kind assistance and suggestion, i have solved it by doing modification at the code below.
private void button5_Click(object sender, EventArgs e)
{
OpenFileDialog ope = new OpenFileDialog();
ope.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
if (ope.ShowDialog() == DialogResult.Cancel)
{
return;
}
FileStream stream = new FileStream(ope.FileName, FileMode.Open);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet ds = excelReader.AsDataSet();
int counter = 1;
var wb = new XLWorkbook();
var worksheet = wb.Worksheets.Add("SINS");
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
if(table.Rows.IndexOf(dr) != 0)
{
string SINs = Convert.ToString(dr[1]);
textBox7.Text = SINs;
Console.WriteLine(SINs); //debug line
Console.WriteLine(counter); //debug line
worksheet.Cell(counter, 1).Value = SINs; //writes to the excel
counter++;
}
}
}
wb.SaveAs("C:\\Users\\WYCHIN\\Desktop\\YONG_TEMP\\DHL API\\Sins.xlsx");
}

Save excel file with Worksheet.SaveAs to any/selected directory

I have figured out how to save my excel file to the specified directory, but when the SaveFileDialog box opens I would like to be able to save anywhere I want. How can I do this?
private void btnExcellExport_Click(object sender, EventArgs e)
{
if (!(dataGridView1.RowCount == 0))
{
if (backgroundWorker1.IsBusy)
return;
using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "Excel Workbook|*.xlsx", RestoreDirectory = true, InitialDirectory = HelpMeClass.GetExcelDirectory
})
{
sfd.FileName = HelpMeClass.SearchString;
if (sfd.ShowDialog() == DialogResult.OK)
{
progressBar1.Show();
progressBar1.Minimum = 0;
progressBar1.Value = 0;
backgroundWorker1.RunWorkerAsync();
}
}
}
else
{
MessageBox.Show("Oops! Nothing to export!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
}
BackgroundWorker:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = excel.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)excel.ActiveSheet;
excel.Visible = true;
int index = 0;
int process = dataGridView1.Rows.Count;
int process1 = dataGridView2.Rows.Count;
int process2 = dataGridView3.Rows.Count;
ws.get_Range("A1", "C1").Merge(); // Merge columns for header
ws.Cells[1, 1] = "Keyword: " + HelpMeClass.SearchString;
ws.Cells[1, 1].Font.Bold = true; // Bold font in header
if (!backgroundWorker1.CancellationPending)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
backgroundWorker1.ReportProgress(index++ * 100 / process);
foreach (DataGridViewCell cell in row.Cells)
{
ws.Cells[index + 1, 1] = cell.Value;
}
}
index = 0;
foreach (DataGridViewRow row in dataGridView2.Rows)
{
backgroundWorker1.ReportProgress(index++ * 100 / process1);
foreach (DataGridViewCell cell in row.Cells)
{
ws.Cells[index + 1, 2] = cell.Value;
}
}
index = 0;
foreach (DataGridViewRow row in dataGridView3.Rows)
{
backgroundWorker1.ReportProgress(index++ * 100 / process2);
foreach (DataGridViewCell cell in row.Cells)
{
ws.Cells[index + 1, 3] = cell.Value;
}
}
}
ws.Columns.AutoFit();
try
{
ws.SaveAs(Path.Combine(HelpMeClass.GetExcelDirectory, HelpMeClass.SearchString), XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
}
catch (Exception ex)
{
MessageBox.Show("Ooops! I can`t access the file. Make sure the excel file is closed and try again. " + ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
return;
}
//excel.Quit();
}
The InitialDirectory gets the path string of public string GetExcelDirectory { get; } = #"C:\Users\" + Environment.UserName + #"\Desktop\"; I would like to have a chance to save the file anywhere I want instead.
Also in SaveAs statement, I`m combining this path with a filename.
I have used this approach instead. I have saved the selected path using Path.GetFirectoryName(sfd.FileName);. Then is a SaveAs I passed that directory and combined with a file name. This works perfectly.
private void btnExcellExport_Click(object sender, EventArgs e)
{
if (!(dataGridView1.RowCount == 0))
{
if (backgroundWorker1.IsBusy)
return;
using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "Excel Workbook|*.xlsx", RestoreDirectory = true, InitialDirectory = HelpMeClass.ExcelSaveDirectory
})
{
sfd.FileName = HelpMeClass.SearchString;
if (sfd.ShowDialog() == DialogResult.OK)
{
HelpMeClass.ExcelSaveDirectory = Path.GetDirectoryName(sfd.FileName);
progressBar1.Show();
progressBar1.Minimum = 0;
progressBar1.Value = 0;
backgroundWorker1.RunWorkerAsync();
}
}
}
else
{
MessageBox.Show("Oops! Nothing to export!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = excel.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)excel.ActiveSheet;
excel.Visible = true;
int index = 0;
int process = dataGridView1.Rows.Count;
int process1 = dataGridView2.Rows.Count;
int process2 = dataGridView3.Rows.Count;
ws.get_Range("A1", "C1").Merge(); // Merge columns for header
ws.Cells[1, 1] = "Keyword: " + HelpMeClass.SearchString;
ws.Cells[1, 1].Font.Bold = true; // Bold font in header
if (!backgroundWorker1.CancellationPending)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
backgroundWorker1.ReportProgress(index++ * 100 / process);
foreach (DataGridViewCell cell in row.Cells)
{
ws.Cells[index + 1, 1] = cell.Value;
}
}
index = 0;
foreach (DataGridViewRow row in dataGridView2.Rows)
{
backgroundWorker1.ReportProgress(index++ * 100 / process1);
foreach (DataGridViewCell cell in row.Cells)
{
ws.Cells[index + 1, 2] = cell.Value;
}
}
index = 0;
foreach (DataGridViewRow row in dataGridView3.Rows)
{
backgroundWorker1.ReportProgress(index++ * 100 / process2);
foreach (DataGridViewCell cell in row.Cells)
{
ws.Cells[index + 1, 3] = cell.Value;
}
}
}
ws.Columns.AutoFit();
try
{
ws.SaveAs(Path.Combine(HelpMeClass.ExcelSaveDirectory, HelpMeClass.SearchString), XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
}
catch (Exception ex)
{
MessageBox.Show("Ooops! I can`t access the file. Make sure the excel file is closed and try again. " + ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
return;
}
//excel.Quit();
}

Import a specific range from CSV file to datagridview

I copied these codes from this link and tried it.
however, it did not work for me. Is there anything wrong with my codes or is there any other way? Or should there be anything to be improved on the codes. The codes are below.
When I have selected the range and pressed ok, nothing happens.
Nothing will appear in my datagridview
private Microsoft.Office.Interop.Excel._Application App;
private Microsoft.Office.Interop.Excel.Range rng = null;
private System.Data.DataTable ConvertRangeToDataTable()
{
try
{
System.Data.DataTable dt = new System.Data.DataTable();
int ColCount = rng.Columns.Count;
int RowCount = rng.Rows.Count;
for (int i = 0; i < ColCount; i++)
{
DataColumn dc = new DataColumn();
dt.Columns.Add(dc);
}
for (int i = 1; i <= RowCount; i++)
{
DataRow dr = dt.NewRow();
for (int j = 1; j <= ColCount; j++)
{
dr[j + 1] = rng.Cells[i, j].Value2;
dt.Rows.Add(dr);
}
}
return dt;
}
catch { return null; }
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog OFD = new OpenFileDialog();
OFD.Filter = "Excel Worksheets|*.xls;*.xlsx;*.xlsm;*.csv";
if (OFD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
App = new Microsoft.Office.Interop.Excel.Application();
App.Visible = true;
App.Workbooks.Open(OFD.FileName);
}
else { return; }
try
{
rng = (Microsoft.Office.Interop.Excel.Range)App.InputBox("Please select a range", "Range Selection");
}
catch { App.Quit(); }; //user pressed cancel on input box
if (rng != null)
{
System.Data.DataTable dt = ConvertRangeToDataTable();
if (dt != null)
{
dataGridView1.DataSource = dt;
}
Dispose();
}
}
private void Dispose()
{
try { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(rng); }
catch { }
finally { rng = null; }
try { App.Quit(); System.Runtime.InteropServices.Marshal.FinalReleaseComObject(App); }
catch { }
finally { App = null; }
}

How to handle result in SaveFileDialog

public void SaveAs()
{
if(dataGridView1.ColumnCount>=2)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File To";
saveFileDialog.ShowDialog();
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += dataGridView1.Columns[i].HeaderText;
}
sw.WriteLine(str);
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dataGridView1.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception e)
{
// MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
else
MessageBox.Show("No data to save", "OK",
MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
When I open the saving window and I decide not to save DataGridView1 by clicking Cancel I have an error Index was outside the bounds of the array. at
myStream = saveFileDialog.OpenFile();
I don't know what's wrong in here.
Your culprit code is here:
saveFileDialog.ShowDialog();
Stream myStream;
myStream = saveFileDialog.OpenFile();
It should be like such:
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
// code here for user pressing OK instead of the 'X' or 'Cancel'
Stream myStream = saveFileDialog.OpenFile();
}
Without that check if you close the dialog (via the 'x') or press Cancel, your saveFileDialog has some "empty" values that you try and reference (which gives you the error).
The function ShowDialog() returns a DialogResult to determine what action was taken. Just check the return value there before you continue. For example:
if(saveFileDialog.ShowDialog() == DialogResult.Cancel)
{
//do something else here or just return
return;
}

Categories