I'm currently attempting to use datagridview for the first time, I have managed to do many things with it so far (such as importing text files) however, I have trouble when attempting to save the datagridview's contents to a text file.
The output I'm currently getting is:
0,
Cat,
Yes,
10,
20,
30,
40,
50,
1,
Dog,
No,
10,
20,
30,
40,
50,
I want the export to look like this:
0, Cat, Yes, 10, 20, 30, 40, 50
1, Dog, No, 10, 20, 30, 40, 50
etc.
This is the code I'm currently using:
using (TextWriter tw = new StreamWriter("example.txt"))
{
for(int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for(int j = 0; j < dataGridView1.Columns.Count; j++)
{
tw.WriteLine($"{dataGridView1.Rows[i].Cells[j].Value.ToString()},");
}
}
}
Anyone here able to help me with this issue? Thank you!
Try the following changes tw.Write() insted of tw.WriteLine():
using (TextWriter tw = new StreamWriter("example.txt"))
{
for(int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for(int j = 0; j < dataGridView1.Columns.Count; j++)
{
tw.Write($"{dataGridView1.Rows[i].Cells[j].Value.ToString()}");
if(!j == dataGridView1.Columns.Count - 1)
{
tw.Write(",");
}
}
tw.WriteLine();
}
}
So, DGV to Text file? This is how I do it.
private void button1_Click(object sender, EventArgs e)
{
//This line of code creates a text file for the data export.
System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\\your_path_here\\sample.txt");
try
{
string sLine = "";
//This for loop loops through each row in the table
for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
{
//This for loop loops through each column, and the row number
//is passed from the for loop above.
for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
{
sLine = sLine + dataGridView1.Rows[r].Cells[c].Value;
if (c != dataGridView1.Columns.Count - 1)
{
//A comma is added as a text delimiter in order
//to separate each field in the text file.
//You can choose another character as a delimiter.
sLine = sLine + ",";
}
}
//The exported text is written to the text file, one line at a time.
file.WriteLine(sLine);
sLine = "";
}
file.Close();
System.Windows.Forms.MessageBox.Show("Export Complete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception err)
{
System.Windows.Forms.MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
file.Close();
}
}
Use tw.Write() instead of tw.WriteLine() until you are finished with all but the last column for the row, then you tw.WriteLine() on the last column data to end the line.
I don't work in C#, but often use these forums as a reference. I develop interfaces for industrial applications. Anyway, the simplest way to do this is through the clipboard. Use the SelectAll() method on your DGV, Throw that DGV data into the Clipboard with the Clipboard.SetDataObject() method, use the File.WriteAllText(), and Clipboard.GetText() methods to write the clipboard text to a file. My code is below. You will notice I have to write out everything from it's namespace so I apologize for it not being exactly how C# is. Note: If you want to make a csv file, DGVs view cell breaks as horizontal tabs (ascii 9). You can do a replace() method for commas. Note: DGV.ClearSelection() is a nice way to finish it off. Note: you may have to enable ClipboardCopyMode on your DGV.
DataGridView1.SelectAll();
System.Windows.Forms.Clipboard.SetDataObject(DataGridView1.GetClipboardContent());
System.IO.File.WriteAllText("File.txt",System.Windows.Forms.Clipboard.GetText());
With the following code you can save and restore the content of every dataGridView.
How to do it:
string sContent = "";
private void btnSaveDataGridViewContent_Click(object sender, EventArgs e)
{
sContent = ReadStringFromDataGridView(ref dataGridView1);
[Write sContent to File/Database/Whatever]
}
private void btnRestoreDataGridViewContent_Click(object sender, EventArgs e)
{
[Read sContent from File/Database/Whatever]
WriteStringToDataGridView(ref dataGridView1, sContent);
}
Helper functions:
string ReadStringFromDataGridView(ref DataGridView MyDataGridView)
{
string sContent = "";
for (int row = 0; row<MyDataGridView.RowCount; row++)
{
if (row > 0) sContent += "\r";
for (int col = 0; col<MyDataGridView.ColumnCount; col++)
{
if (col > 0) sContent += ";";
sContent += MyDataGridView[col, row].Value;
}
}
return sContent;
}
void WriteStringToDataGridView(ref DataGridView MyDataGridView, string sContent)
{
MyDataGridView.Rows.Clear();
string[] Rows = sContent.Split("\r".ToCharArray());
for (int row=0; row<Rows.Length; row++)
{
MyDataGridView.RowCount = Rows.Length;
string[] Cols = Rows[row].Split(";".ToCharArray());
for (int col=0; col<Cols.Length; col++)
{
MyDataGridView[col, row].Value = Cols[col];
}
}
}
string file = "C:\\Users\\Sangeeth\\Desktop\\Excel.txt";
using (TextWriter tw = new StreamWriter(file))
{
int i, j = 0;
for(i = 0; i < dataGridView1.Rows.Count -1; i++)
{
for (j = 0; j < dataGridView1.Columns.Count; j++)
{
tw.Write($"{dataGridView1.Rows[i].Cells[j].Value.ToString()}");
tw.Write(",");
}
tw.WriteLine(" ");
}
}
Related
On one of my WebPages I have placed FileUpload1 item, in which I would like to store CSV file and then analyze it. However I can't read it in, an Exception is thrown. It seems like the filepath changes (I have file store on Desktop, whereas it displays that the file is searched in C:\Program Files (x86)\IIS Express).
protected void Button2_Click(object sender, EventArgs
{
Response.Write("Jestem w petli file.hasfile");
if (FileUpload1.PostedFile != null)
{
string filePath = FileUpload1.PostedFile.FileName;
StreamReader reader = new StreamReader(filePath);
string[] readLines = new string[7];
int dayOfWeek = 0;
while (dayOfWeek < 7)
{
do
{
string textLine = reader.ReadToEnd();
readLines[dayOfWeek] = textLine;
}
while (reader.Peek() != -1);
dayOfWeek++;
}
for(int i = 0; i < 7; i++)
{
generateData(readLines[i], i);
}
reader.Close();
}
for(int i = 0; i < 7; i++)
{
TableRow tblRow = new TableRow();
Table1.Rows.Add(tblRow);
for (int j = 0; j < 2; j++)
{
TableCell tCell = new TableCell();
tCell.Text = positionsInWtr[i, j];
tblRow.Cells.Add(tCell);
}
}
}
Could you tell me what I am doing wrong?
Thanks in advance,
Kokos
I've made a Password manager app.
Im trying to only export Name, Username, Password and Chaged date rows.
But for now, it also export the column buttons.
Any hints?
When I Export with this code:
private void exportToPDFToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Pdf File |*.pdf";
if (sfd.ShowDialog() == DialogResult.OK)
{
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
doc.Open();//Open Document to write
Paragraph paragraph = new Paragraph("data Exported From PassVault!\n\n");
PdfPTable table = new PdfPTable(dgvPasswords.Columns.Count);
//Add the headers
for (int j = 0; j < dgvPasswords.Columns.Count; j++)
{
table.AddCell(new Phrase(dgvPasswords.Columns[j].HeaderText));
}
//Flag the first row as header
table.HeaderRows = 1;
//Add the actual rows from the DGV to the table
for (int i = 0; i < dgvPasswords.Columns.Count; i++)
{
for (int k = 0; k < dgvPasswords.Rows.Count; k++)
{
if (dgvPasswords[k, i].Value != null)
{
table.AddCell(new Phrase(dgvPasswords[k, i].Value.ToString()));
}
}
}
doc.Add(paragraph);
doc.Add(table);
doc.Close();
// MessageBox.Show("Exported as Export-List.pdf to \n\n" + Application.StartupPath + " /Export-List.pdf", "PDF Exported", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
It also includes the column Copy and Column New button..
Made It perfect, but now Im not sure where I did miss.
How do I only export: Name, Username, Password and Changed Date from DgvPassword?
You are attempting to access outside the bounds of the dgvPasswords array due to using the incorrect upper limit for k
for (int k = 0; k < dgvPasswords.Columns.Count; k++)
{
should read
for (int k = 0; k < dgvPasswords.Rows.Count; k++)
{
private void write(object sender, EventArgs e)
{
FileStream outputFileStream = new FileStream("test.txt", FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(outputFileStream);
Random r = new Random();
for (int i = 0; i < dataGridView1.RowCount; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
double d = 0;
Double.TryParse(Convert.ToString(dataGridView1.Rows[i].Cells[j].Value), out d);
writer.Write(d + "\t");
}
writer.Write("\n");
}
writer.Close();
outputFileStream.Close();
}
So this is the method to write the text file. It works fine because I have opened it successfully with an Excel. I even tried to copy and paste it and it would work. Now the problem is.....
private void read(object sender, EventArgs e)
{
char TAB = '\t';
char NEWLINE = '\n';
FileStream inputFileStream = new FileStream("test.txt", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(inputFileStream);
string line;
string[] fields;
for (int i = 0; i < dataGridView1.RowCount; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
line = reader.ReadLine();
fields = line.Split(TAB, NEWLINE);
dataGridView1.Rows[i].Cells[j].Value = fields;
}
}
inputFileStream.Close();
reader.Close();
}
However when I read the file back onto a DataGridView it does not work properly. Now this is the exact text file that I wrote on my code. Instead what happens is that it is displayed on only 1 row. How do I get back the amount of columns and rows from what the user entered? I prefer keeping it a text file.
I have used default properties for my dataGridView1
RowCount returns displayed rows count. So here it returns 1 because you are displaying one row and it's empty:
for (int i = 0; i < dataGridView1.RowCount; i++)
Instead of this, you should create new rows and add it to the Rows collection like this:
// Use File.ReadAllLines, it's easier
string[] lines = File.ReadAllLines("test.txt");
foreach(line in lines)
{
var text = line.Split('\t','\n');
dataGridView1.Rows.Add(text);
}
System.IO.StreamReader file = new System.IO.StreamReader("yourfile.txt");
string[] columnnames = file.ReadLine().Split(' ');
DataTable dt = new DataTable();
foreach (string c in columnnames)
{
dt.Columns.Add(c);
}
string newline;
while ((newline = file.ReadLine()) != null)
{
DataRow dr = dt.NewRow();
string[] values = newline.Split(' ');
for (int i = 0; i < values.Length; i++)
{
dr[i] = values[i];
}
dt.Rows.Add(dr);
}
file.Close();
dataGridView1.DataSource = dt;
try this one with your own delimiters i.e. \t and \n. And First try to search your problems on internet before posting queries and try to solve them by yourself. I am not giving full code.
How can I read data from DataGridView in C#? I want to read the data appear in Table. How do I navigate through lines?
something like
for (int rows = 0; rows < dataGrid.Rows.Count; rows++)
{
for (int col= 0; col < dataGrid.Rows[rows].Cells.Count; col++)
{
string value = dataGrid.Rows[rows].Cells[col].Value.ToString();
}
}
example without using index
foreach (DataGridViewRow row in dataGrid.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
string value = cell.Value.ToString();
}
}
If you wish, you can also use the column names instead of column numbers.
For example, if you want to read data from DataGridView on the 4. row and the "Name" column.
It provides me a better understanding for which variable I am dealing with.
dataGridView.Rows[4].Cells["Name"].Value.ToString();
Hope it helps.
string[,] myGridData = new string[dataGridView1.Rows.Count,3];
int i = 0;
foreach(DataRow row in dataGridView1.Rows)
{
myGridData[i][0] = row.Cells[0].Value.ToString();
myGridData[i][1] = row.Cells[1].Value.ToString();
myGridData[i][2] = row.Cells[2].Value.ToString();
i++;
}
Hope this helps....
Code Example : Reading data from DataGridView and storing it in an array
int[,] n = new int[3, 19];
for (int i = 0; i < (StartDataView.Rows.Count - 1); i++)
{
for (int j = 0; j < StartDataView.Columns.Count; j++)
{
if(this.StartDataView.Rows[i].Cells[j].Value.ToString() != string.Empty)
{
try
{
n[i, j] = int.Parse(this.StartDataView.Rows[i].Cells[j].Value.ToString());
}
catch (Exception Ee)
{ //get exception of "null"
MessageBox.Show(Ee.ToString());
}
}
}
}
private void HighLightGridRows()
{
Debugger.Launch();
for (int i = 0; i < dtgvAppSettings.Rows.Count; i++)
{
String key = dtgvAppSettings.Rows[i].Cells["Key"].Value.ToString();
if (key.ToLower().Contains("applicationpath") == true)
{
dtgvAppSettings.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
}
}
}
I have this loop, which I am using to get the values of all cells within all rows of a gridview and then write it to a csv file. My loop looks like this:
string filename = #"C:\Users\gurdip.sira\Documents\Visual Studio 2008\WebSites\Supressions\APP_DATA\surpressionstest.csv";
StreamWriter sWriter = new StreamWriter(filename);
string Str = string.Empty;
string headertext = "";
sWriter.WriteLine(headertext);
for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++)
{
for (int j = 0; j <= (this.GridView3.Columns.Count - 1); j++)
{
Str = this.GridView3.Rows[i].Cells[j].Text.ToString();
sWriter.Write(Str);
}
sWriter.WriteLine();
}
sWriter.Close();
The problem with this code is that, when stepping through, the 2nd loop (the one going through the columns) does not begin as the debugger does not hit this loop and thus my file is empty.
Any ideas on what is causing this? The code itself looks fine.
Thanks
I think the inner loop should access the Cells, not the columns:
for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++)
{
for (int j = 0; j <= (this.GridView3.Rows[i].Cells.Count - 1); j++)
{
Str = this.GridView3.Rows[i].Cells[j].Text.ToString();
sWriter.Write(Str);
}
}
Adding in line numbers, if I understand your question correctly, you're saying that when debugging, you never reach line 8. If that is the case then I would expect your issue is that when you're actually processing through the loop there are no rows in your gridview. To figure out why that is the case, I would recommend looking at where you are in the post cycle for your page
string filename = #"C:\Users\gurdip.sira\Documents\Visual Studio 2008\WebSites\Supressions\APP_DATA\surpressionstest.csv";//1
StreamWriter sWriter = new StreamWriter(filename);//2
string Str = string.Empty;//3
string headertext = ""; //4
sWriter.WriteLine(headertext); //5
for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++) //6
{ //7
for (int j = 0; j <= (this.GridView3.Columns.Count - 1); j++) //8
{ //9
Str = this.GridView3.Rows[i].Cells[j].Text.ToString();//10
sWriter.Write(Str);//11
}//12
sWriter.WriteLine();//13
}//14
sWriter.Close();//15
}//16