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

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();
}

Related

C# Excel to .TXT

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;
}
}
}

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; }
}

xml load after exporting excel file failed

I have a c# application with the following features:
read a password from a config file.
export an Excel file.
when I read the password at fist: it's ok. but once I export the Excel file, I can't no more read the password from config file. the following instruction fail.
xmlDoc.Load("Cfg.xml");
this issue appear only on Windows XP. on windows 7 it's ok.
the code for reading password from config file:
private void OK_Click(object sender, EventArgs e)
{
try
{
// Check password
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Cfg.xml");
XmlNode node = xmlDoc.SelectSingleNode("Config/ManagerPW");
if (node != null)
{
string MangerPW = node.Attributes[0].Value;
PCCrypto PWCrypto = new PCCrypto();
if (PWCrypto.verifyMd5(this.Password.Text, MangerPW) == true)
{
isCorrectPassWord = true;
this.Dispose();
}
else
{
MessageBox.Show("Incorrect Password!", "PW Authentication", MessageBoxButtons.OK,
MessageBoxIcon.Error);
this.Password.Text = "";
}
}
else
{
MessageBox.Show("You tried to perform an unauthorized operation!", "PW Authentication", MessageBoxButtons.OK,
MessageBoxIcon.Error);
this.Password.Text = "";
}
}
catch
{
MessageBox.Show("Error in loading configuration file", "Configuration Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
this.Dispose();
}
}
the code of exporting Excel file
public bool exportToExcel(string path)
{
bool bRet = true;
int columnsNum = resultList.Columns.Count - 1;
int rowsNum = resultList.Items.Count;
object[,] array = new object[rowsNum + 1, columnsNum];
//Change Current System Time to US
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
Excel.Application xlApp = new Excel.ApplicationClass();
Excel.Workbooks xlWorkBooks = xlApp.Workbooks;
Excel.Workbook xlWorkBook = xlWorkBooks.Add(Type.Missing);
Excel.Sheets xlWorkSheets = xlWorkBook.Sheets;
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkSheets[1];
//disable alerts
xlApp.DisplayAlerts = false;
//Add Header to array
for (int i = 0; i < columnsNum; i++)
{
array[0, i] = resultList.Columns[i + 1].Text;
}
//Add Listview data to array
for (int r = 0; r < rowsNum; r++)
{
for (int c = 0; c < columnsNum; c++)
{
this.Invoke(new MethodInvoker(delegate
{
array[r + 1, c] = resultList.Items[r].SubItems[c+1].Text;
}));
}
}
//Save array data into excel
Excel.Range c1 = (Excel.Range)xlWorkSheet.Cells[1, 1];
Excel.Range c2 = (Excel.Range)xlWorkSheet.Cells[rowsNum + 1, columnsNum];
Excel.Range xlRange = xlWorkSheet.get_Range(c1, c2);
xlRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
xlRange.EntireColumn.NumberFormat = "#";
xlRange.Value2 = array;
xlRange.EntireColumn.AutoFit();
//Add Header color
xlWorkSheet.get_Range("A1", "I1").Interior.Color = ColorTranslator.ToOle(Color.Aquamarine);
//Save Excel file
try
{
xlWorkBook.SaveAs(#path, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Close(true, Type.Missing, Type.Missing);
}
catch
{
bRet = false;
}
xlWorkBooks.Close();
xlApp.Application.Quit();
xlApp.Quit();
releaseObject(c1);
releaseObject(c2);
releaseObject(xlRange);
releaseObject(xlWorkSheet);
releaseObject(xlWorkSheets);
releaseObject(xlWorkBook);
releaseObject(xlWorkBooks);
releaseObject(xlApp);
return bRet;
}
Try specifying the full path in
xmlDoc.Load("Cfg.xml");
e.g.
xmlDoc.Load(#"C:\myfolder\Cfg.xml");
The current folder is being changed when you export the excel.

ContextMenu Click Event firing more than once

This is really strange, for some reason my contextmenu clicks are firing more than once. I have the contextmenu tied to a button, so when the button is clicked the contextmenu is shown under it (with more options).
One option is to save listview to Excel, the other is to save to .csv.
So basically what happens here is that multiple excel sheets will open. Of course I only want one excel to open :)
Here is my code:
private void toolButtonNoBorder3_Click(object sender, EventArgs e)
{
contexMenuuu.Show(toolButtonNoBorder3,
new Point(0, toolButtonNoBorder3.Height));
contexMenuuu.ItemClicked +=
new ToolStripItemClickedEventHandler(contexMenuuu_ItemClickedd);
}
void contexMenuuu_ItemClickedd(object sender, ToolStripItemClickedEventArgs e)
{
contexMenuuu.Hide();
contexMenuuu.Close();
if (e.ClickedItem.Text == "Excel")
{
Microsoft.Office.Interop.Excel.Application app =
new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;
Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(1);
Microsoft.Office.Interop.Excel.Worksheet ws =
(Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];
int i = 1;
int i2 = 1;
int iad = 1;
foreach (ListViewItem lvi in flatListView1.Items)
{
i = 1;
foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
{
if (i2 == 1)
{
iad = 1;
foreach (ColumnHeader lvfi in flatListView1.Columns)
{
try
{
ws.Cells[i2, iad] = lvfi.Text;
}
catch (Exception ee)
{
}
iad++;
}
}
else
{
try
{
ws.Cells[i2, i] = lvs.Text;
}
catch (Exception ee)
{
}
}
i++;
}
i2++;
}
}
else if (e.ClickedItem.Text == "CSV")
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "csv files (*.csv)|*.csv";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
myStream.Close();
ListViewToCSV(flatListView1, saveFileDialog1.FileName, true);
}
}
}
}
It should be in a constructor of your window:
public MyWindow()
{
//here inicialization
contexMenuuu.ItemClicked +=
new ToolStripItemClickedEventHandler(contexMenuuu_ItemClickedd);
}
This is a very common error to add event handler more than once, be careful next time
In my case I have solved it using following statement -
e.Handled = true;
This will mark the event as handled (Obviously).

DataGridView Printing

How do I print specified rows out to a file from a DataGridView?
Also how can I print out certain columns?
This is what I have been trying to work with.. but it is not working..:
private void saveButton_Click(object sender, EventArgs e)
{
saveFile1.DefaultExt = "*.txt";
saveFile1.Filter = ".txt Files|*.txt|All Files (*.*)|*.*";
saveFile1.RestoreDirectory = true;
if (saveFile1.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(saveFile1.FileName);
List<string> theList = new List<string>();
foreach (var line in theFinalDGV.Rows)
{
if (line.ToString().Contains("FUJI"))
richTextBox1.AppendText(line + "\n");
}
}
}
Can anyone help me in the right direction?
DataGridViewRow.ToString() only gives you the typename back, not the row content. You can use this extender to get the rowcontent ('ColumnName'):
public static class Extender {
public static string RowToString(this DataGridViewRow dgvr) {
string output = "";
DataGridView dgv = dgvr.DataGridView;
foreach (DataGridViewCell cell in dgvr.Cells) {
DataGridViewColumn col = cell.OwningColumn;
output += col.HeaderText + ":" + cell.Value.ToString() + ((dgv.Columns.IndexOf(col) < dgv.Columns.Count - 1) ? ", " : "");
}
return output;
}
}
if you only want the content of the row without the coulmn-headername use this (space separated):
public static class Extender {
public static string RowToString(this DataGridViewRow dgvr) {
string output = "";
foreach (DataGridViewCell cell in dgvr.Cells) {
output += cell.Value.ToString() + " ";
}
return output.TrimEnd();
}
}
your code will look like this:
class YourClass
{
private void saveButton_Click(object sender, EventArgs e)
{
saveFile1.DefaultExt = "*.txt";
saveFile1.Filter = ".txt Files|*.txt|All Files (*.*)|*.*";
saveFile1.RestoreDirectory = true;
if (saveFile1.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(saveFile1.FileName);
List<string> theList = new List<string>();
foreach (var line in theFinalDGV.Rows)
{
string linecontent = line.RowToString();
if (linecontent.Contains("FUJI"))
richTextBox1.AppendText(linecontent + "\n");
}
}
}
}
public static class Extender {
public static string RowToString(this DataGridViewRow dgvr) {
string output = "";
DataGridView dgv = dgvr.DataGridView;
foreach (DataGridViewCell cell in dgvr.Cells) {
DataGridViewColumn col = cell.OwningColumn;
output += col.HeaderText + ":" + cell.Value.ToString() + ((dgv.Columns.IndexOf(col) < dgv.Columns.Count - 1) ? ", " : "");
}
return output;
}
}

Categories