I have problem with write listView to txt, my code write all columns (first and second) to txt.
I have this code:
using (StreamWriter sw = new StreamWriter("databaseEN.txt"))
{
foreach (ListViewItem item in listView1.Items)
{
sw.WriteLine(item.Text);
for (int i = 1; i < item.SubItems.Count; i++)
{
sw.WriteLine(item.SubItems[i].Text);
}
}
}
I need write first column not all column to my txt, how change this?
A ListViewItem contains many SubItems, which you can access from your item variable.
item.SubItems[0].Text;
This will get only the first column. You can also specify a column name as a string.
This is what I came up with. It works for me. It looks long because of the coments and the new lines added so it looks good in the text file when it gets saved.
// Save File Button
private void save_button_Click(object sender, EventArgs e)
{
System.IO.File.AppendAllText(#"C:\bbbb.txt", Environment.NewLine + Environment.NewLine);
// Columns NAMES
for (int c = 0; c < timeTable_listView.Columns.Count; c++)
{
System.IO.File.AppendAllText(#"C:\bbbb.txt", timeTable_listView.Columns[c].Text+"\t");
}
// Add new Line int the txt file
System.IO.File.AppendAllText(#"C:\bbbb.txt", Environment.NewLine + Environment.NewLine);
// Get all Items "loop All items"
for (int i = 0; i < timeTable_listView.Items.Count; i++)
{
// Loop all Sub Items of the Current Item "[i]"
for (int a = 0; a < timeTable_listView.Items[i].SubItems.Count; a++)
{
// Write the sub item "[a]" to the file with "tab betwen each item"
System.IO.File.AppendAllText(#"C:\bbbb.txt", timeTable_listView.Items[i].SubItems[a].Text + "\t");
}
// Add new Line "the new Row" starts at new line
System.IO.File.AppendAllText(#"C:\bbbb.txt", Environment.NewLine);
}
}
Iamege: Form
Image: TXT File
ONLY CODE:----------------------------------------------------------------
private void save_button_Click(object sender, EventArgs e)
{
System.IO.File.AppendAllText(#"C:\bbbb.txt", Environment.NewLine + Environment.NewLine);
for (int c = 0; c < timeTable_listView.Columns.Count; c++)
{
System.IO.File.AppendAllText(#"C:\bbbb.txt", timeTable_listView.Columns[c].Text+"\t");
}
System.IO.File.AppendAllText(#"C:\bbbb.txt", Environment.NewLine + Environment.NewLine);
for (int i = 0; i < timeTable_listView.Items.Count; i++)
{
for (int a = 0; a < timeTable_listView.Items[i].SubItems.Count; a++)
{
System.IO.File.AppendAllText(#"C:\bbbb.txt", timeTable_listView.Items[i].SubItems[a].Text + "\t");
}
System.IO.File.AppendAllText(#"C:\bbbb.txt", Environment.NewLine);
}
}
Delete this lines:
for (int i = 1; i < item.SubItems.Count; i++)
{
sw.WriteLine(item.SubItems[i].Text);
}
EDIT: Extracted from here http://msdn.microsoft.com/en-us/library/aa983553(v=vs.71).aspx
The Windows Forms ListView control can display additional text, or
subitems, for each item in the Details view. The first column displays
the item text, for example an employee number. The second, third, and
subsequent columns display the first, second, and subsequent
associated subitems.
Related
I am trying to create a string with items from a ListView in C#(Windows Forms). I have two columns and over hundreds of three digit numbers in my ListView. The values indicate which X and Y axis my mouse was on. But as soon as I try to output the values in e.g. a text box, only the last X and Y values appear, the rest are ignored.
What I have tried:
listView1.Items[a].SubItems[0].Text
int.Parse(listView1.Items[a].SubItems[0].Text)
maybe someone has a suggestion
You need to iterate over the items and subitems in this manner:
foreach (ListViewItem item in listView1.Items)
{
Debug.WriteLine($"Item: {item.Text}");
foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
{
Debug.WriteLine($"\tSubitem:{subitem.Text}");
}
}
Do you use a loop for your items? It's not clear where a comes from. You might also want to use a loop for your subitems.
you can loop through all items and subitems like this:
for (int i = 0; i < listView1.Items.Count; i++)
{
for (int k = 0; k < listView1.Items[i].SubItems.Count; k++)
{
string s = listView1.Items[i].SubItems[k].Text;
}
}
thanks for your help guys,
the only thing missing was the loop and this line Value += Environment.NewLine +
your suggestions both worked
foreach (ListViewItem item in listView1.Items)
{
Value += Environment.NewLine + item.Text;
foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
{
Value += Environment.NewLine + subitem.Text;
}
}
and
for (int i = 0; i < listView1.Items.Count; i++)
{
for (int k = 0; k < listView1.Items[i].SubItems.Count; k++)
{
Value += Environment.NewLine + listView1.Items[i].SubItems[k].Text;
}
}
The follwoing code is used by me to print entires in a datagrid view into text file by converting them into strings! The data grid view has 3 columns(3rd column has several strings) and I want to print each data grid view row as a single line in the text file!
private void button1_Click_1(object sender, EventArgs e) // converting data grid value to single string
{
String file = " " ;
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 0; j < dataGridView2.Rows[i].Cells.Count; j++)
{
if (dataGridView2.Rows[i].Cells[j].Value != null)
{
if (j == 0)
{
file = Environment.NewLine + file + dataGridView2.Rows[i].Cells[j].Value.ToString();
}
else
{
file = file + dataGridView2.Rows[i].Cells[j].Value.ToString();
}
}
}
using (StreamWriter sw = new StreamWriter(#"C:\Users\Desktop\VS\Tfiles\file.txt"))
{
{
sw.Write(file);
}
}
}
}
Though a textfile is created the first 2 columns and the 1st string in the 3rd column are printed on the same line but the other strings of the 3rd column are printed on a new line! how can i get them onto the same line.
eg- let a sample data grid view row be like (aaa) (bbb) (ccc dddd eee) and it must appear in the textfile as aaa bbb ccc dddd eee but from my code it appears like aaa bbb ccc on the sameline, dddd on a new line and eee on another new line! how can i correct this issue?
Instead of relying on j==0, you can append new line outside of inner for loop. Also to put in that many string values you should really use StringBuilder. Try this:
private void button1_Click_1(object sender, EventArgs e) // converting data grid value to single string
{
StringBuilder file = new StringBuilder();
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 0; j < dataGridView2.Rows[i].Cells.Count; j++)
{
var val = dataGridView2.Rows[i].Cells[j].Value;
if (val == null)
continue;//IF NULL GO TO NEXT CELL, MAYBE YOU WANT TO PUT EMPTY SPACE
var s=val.ToString();
file.Append(s.Replace(Environment.NewLine," "));
}
file.AppendLine();//NEXT ROW WILL COME INTO NEXT LINE
}
using (StreamWriter sw = new
StreamWriter(#"C:\Users\Desktop\VS\Tfiles\file.txt"))
{
sw.Write(file.ToString());
}
}
EDIT:- Seems 3rd column contains strings with new line so we can remove the new line from string before putting to file:
var s = val.ToString();
file.Append(s.Replace(Environment.NewLine, " "));
Try this:
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
for (int j = 0; j < dataGridView2.Rows[i].Cells.Count; j++)
{
if (dataGridView2.Rows[i].Cells[j].Value != null)
{
file = file + dataGridView2.Rows[i].Cells[j].Value.ToString();
}
}
I would like to output only a part of items from listBox1 like:response.response.items[counter].first_name to lable_name.Text. How can I do that?
Part of method:
for (int counter = 0; counter < response.response.items.Count; counter++)
{
listBox1.Items.Add(response.response.items[counter].first_name + " " + response.response.items[counter].last_name + Environment.NewLine);
}
The way I output items to lable:
private void listBox1_DoubleClick(object sender, EventArgs e)
{
int count = listBox1.Items.Count -1;
for (int counter = count; counter >= 0; counter--)
{
if (listBox1.GetSelected(counter))
{
lable_name.Text= listBox1.Items[counter].ToString();
}
}
}
lable_name.Text = listbox1.Items[counter].ToString().Split(' ')[0];
could be one of the options ...
just make sure what charackter are qou spliting on as well as the text in string.
private void open(object sender, EventArgs e)
{
// only works for opening the table
dataGridView1.Rows.Clear();
OpenFileDialog openDialog = new OpenFileDialog();
if (openDialog.ShowDialog() == DialogResult.OK)
{
fileLabel.Text = openDialog.FileName;
// Use File.ReadAllLines, it's easier
string[] lines = File.ReadAllLines(openDialog.FileName);
foreach (string line in lines)
{
var text = line.Split(',', '\n');
dataGridView1.Rows.Add(text);
}
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
dataGridView1.Rows[i].HeaderCell.Value = (i + 1).ToString();
}
}
}
This is currently my code for opening and reading. So I also have the writing code (actually I wrote a text file already) and I want to add in a few more pieces of information somewhere on the form but not on the dataGridView1
Now in my previous version I had the following code added for reading the extra lines of a text file.
int k = 0;
while (k < lines.Length)
{
for (int j = 0; j < twoDTextBox.GetLength(0); j++)
{
for (int i = 0; i < twoDTextBox.GetLength(1); i++)
{
statsBonus[j, i].Text = lines[k];
k++;
}
}
// these lines I would like to add to read in my new file
textBox1.Text = lines[k];
k++;
comboBox1.SelectedItem = lines[k];
k++;
checkBox1.Checked = Convert.ToBoolean(lines[k]);
k++;
}
Before I used to use textboxes but later found out it wasn't really efficient and dynamic.
So now how do I add the bottom lines to my form after reading the DataGridView lines?
I have a DataGridView and I want to save its content to a CSV file. Then when I run the program again it loads the data from the CSV file to the gridview.
I have this code to save to CSV file:
private void button1_Click(object sender, EventArgs e)
{
FileInfo todel = new FileInfo(#"c:\dd\GB STOCK.csv");
todel.Delete();
int cols;
//open file
StreamWriter wr = new StreamWriter(#"c:\dd\GB STOCK.csv");
//determine the number of columns and write columns to file
cols = dataGridView1.Columns.Count;
for (int i = 0; i < cols ; i++)
{
wr.Write(dataGridView1.Columns[i].Name.ToString().ToUpper() + ",");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (dataGridView1.Rows.Count - 1); i++)
{
for (int j = 0; j < cols; j++)
{
if (dataGridView1.Rows[i].Cells[j].Value != null)
{
wr.Write(dataGridView1.Rows[i].Cells[j].Value + ",");
}
else
{
wr.Write(",");
}
}
wr.WriteLine();
}
//close file
wr.Close();
}
And this code to load from the csv to the gridview:
private void Form1_Load(object sender, EventArgs e)
{
string rowValue;
string[] cellValue;
if (System.IO.File.Exists(#"C:\dd\GB STOCK.csv"))
{
System.IO.StreamReader streamReader = new StreamReader(#"C:\dd\GB STOCK.csv");
// Reading header
rowValue = streamReader.ReadLine();
cellValue = rowValue.Split(',');
for (int i = 0; i <= cellValue.Count() - 1; i++)
{
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.Name = cellValue[i];
column.HeaderText = cellValue[i];
dataGridView1.Columns.Add(column);
}
// Reading content
while (streamReader.Peek() != -1)
{
rowValue = streamReader.ReadLine();
cellValue = rowValue.Split(',');
dataGridView1.Rows.Add(cellValue);
}
streamReader.Close();
}
else
{
MessageBox.Show("No File is Selected");
}
}
now the problem is that whenever I save and load the gridview it adds one extra column (without header) every time.
Could anybody tell me what is the wrong with this code?
When you save you are ending the line with a comma. So when the file gets read back in it thinks there is an extra (empty) value on the end. Try:
rowValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
While Saving the Data grid values to CSV, Check the Count of Grid view Column (How much its coming.? and How much column is actually.?) In Your button1_Click.
Carefully debug your code.
Have you tried Something like this in your button1_Click also:
`cols = dataGridView1.Columns.Count - 1;`
Or
for (int i = 0; i < cols - 1; i++)
{
wr.Write(dataGridView1.Columns[i].Name.ToString().ToUpper() + ",");
}