Reputation: 4292
I have a DataGridView in a UI (win form) and now wants to write data in the grid to a text file.
I've tried it with following code. But its not giving the output what I want.
public void WriteToTextFile (DataGridView dgv)
{
string file_name = "D:\\test1.txt";
System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(file_name);
int count = dgv.Rows.Count;
for (int row = 0; row < count-1; row++)
{
int colCount = dgv.Rows[row].Cells.Count;
for ( int col = 0; col < colCount-1; col++)
{
objWriter.WriteLine(dgv.Rows[row].Cells[col].Value.ToString());
}
// record seperator could be written here.
}
objWriter.Close();
}
Output (only a single item (one grid row) is shown)
8130201489
D.I.S.Peter
292331pslr
0100507563
Sharpe Eyes Pvt Ltd
A002
SalaryFeb11
110228
But the required out put is... (not this should be a single line )
8130201489D.I.S.PETER 2923319SLR0100507563SHARPEYES PVT LTD A002 SALARYFEB11 110228 @
How to modify the above code to get this out put?
Also if I need some additional spaces between words how to insert it? After writing I want to change the extension .txt
to .dat
How to do that.
Upvotes: 1
Views: 1454
Reputation: 11025
Do not write every value with WriteLine()
. Instead, construct each line using a StringBuilder, and then write the complete line as output:
using System.IO;
using System.Text;
public void WriteToTextFile (DataGridView dgv)
{
String file_name = "D:\\test1.txt";
using (StreamWriter objWriter = new StreamWriter(file_name))
{
for (Int32 row = 0; row < dgv.Rows.Count - 1; row++)
{
StringBuilder sb = new StringBuilder();
for (Int32 col = 0; col < dgv.Rows[row].Cells.Count - 1; col++)
{
if (!String.IsNullOrEmpty(sb.ToString()))
sb.Append(","); //any delimiter you choose
sb.Append(dgv.Rows[row].Cells[col].Value.ToString().ToUpper());
}
objWriter.WriteLine(sb.ToString());
}
}
//Rename the file
File.Move(file_name, Path.ChangeExtension(file_name, "dat")); //with or without a leading period
}
Upvotes: 1