Display contents of Textfile data to ListView in C# - c#

I have a listview in my form.
In my text file I have this:
24-7-2017:13:44:40;x;0.0078;y;-0.0147;z;0.9879;
24-7-2017:13:44:41;x;0.0069;y;-0.0069;z;1.0104;
24-7-2017:13:44:40; represents the time where I want to put in the first column of the listview
x;0.0078;y;-0.0147;z;0.9879; is where I want to create three columns to put the X,Y,Z in the each column and the data in the respective column
the next line will then be in row 2 in their respective column
they are separated by ";"
How I go about displaying it in the listview?

Try this
System.Windows.Forms.ListView listView = new System.Windows.Forms.ListView();
DateTime = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
X = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
Y = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
Z = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
SuspendLayout();
listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
DateTime,
X,
Y,
Z});
listView.GridLines = true;
listView.View = System.Windows.Forms.View.Details;
DateTime.Text = "DateTime";
X.Text = "X";
Y.Text = "Y";
Z.Text = "Z";
this.Controls.Add(this.listView);
StreamReader file = new StreamReader("filepath");
string sLine;
while ((sLine = file.ReadLine()) != null)
{
string[] sarr= sLine.Split(';');
StringBuilder sb = new StringBuilder(sarr[0]);
sb[sarr[0].IndexOf(':')] = ' ';
sarr[0] = sb.ToString().Replace(':', '.');
string[] sData = { sarr[0], sarr[2], sarr[4], sarr[6] };
ListViewItem item = new ListViewItem(sData);
listView.Items.Add(item);
}
after this you can add your first data into listView and then do for remain the same. And make sure your listView view property set to Details.
output:

Here is the new tested answer with the solution.
public Form1()
{
InitializeComponent();
//read the file
System.IO.StreamReader file =
new System.IO.StreamReader("yourFileName.txt");
//set list view in details mode
listView1.View = View.Details;
//Set columns in listview
listView1.Columns.Add("Date Time");
listView1.Columns.Add("X");
listView1.Columns.Add("Y");
listView1.Columns.Add("Z");
string line = "";
//read text file line by line.
while (( line = file.ReadLine()) != null)
{
var itemMC = new ListViewItem(new[] { line.ToString().Split(';')[0].ToString(), line.ToString().Split(';')[2].ToString(),
line.ToString().Split(';')[4].ToString(), line.ToString().Split(';')[6].ToString() });
listView1.Items.Add(itemMC);
}
file.Close();
}
Here is the output(from the given data in question) :

Related

How to I set a string variable that has CR\LF's into a Winform textbox?

I have a Winforms textbox set to AcceptReturns = true, Scrollbars = vertical, Multiline = true.
I construct a string called note by looping thru a datatable, putting the value into note with: note = note plus a "\n\n".
When I view the string with the text visualizer, it shows the CR\LF's correctly but after the command: remarks.text = note, the textbox DOES NOT have the CR\LF's.
How do I get the CR\LF's to be respected?
int x = 0;
string note = "";
command = null;
DataTable dtnew = new DataTable();
foreach (string rcd in app.feecd) // app.feecd is an array established earlier in code
{
command = GetConnectedClass.newsqlconnection("SELECT NoteDesc from dbo.inspnote where NoteCode = #selcode");
command.Parameters.AddWithValue("#selcode", rcd);
dtnew.Load(command.ExecuteReader());
note = note + dtnew.Rows[x].Field<string>("NoteDesc") + "\n\n";
command = null;
x = x + 1;
}
if (remarks.Text == "")
{ remarks.Text = note; } // note has CR\LF but remarks.Text NO CR\LF ????
else { remarks.Text = remarks.Text + "\n\n" + note; }

c# - Trying to populate textbox and listview from txt file

I'm only able to load the textbox and can't seem to get the listview to populate. But, after I remove this.textBox1.Text = sr.ReadToEnd(); listview has populated. Here's code:
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
string line = String.Empty;
this.textBox1.Text = sr.ReadToEnd(); // remove it, listview working
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(new char[0]);
ListViewItem item = new ListViewItem
{
Text = data[0]
};
item.SubItems.Add(data[1]);
listView1.Items.Add(item);
}
}
Screenshots:
Img1
Img2
Well, sr.ReadToEnd() reads the file upto its end, and that's why ReadLine() is of no use.
Let's read the file line by line and update text (which we'll assign to this.textBox1.Text) and listView1.Items:
StringBuilder text = new StringBuilder();
bool firstLine = true;
// We don't want redrawing after each ListViewItem adding
listView1.BeginUpdate();
try {
// File.ReadLines is easier to manipulate with StreamReader
// if you want just read lines
foreach (string line in File.ReadLines(openFileDialog1.FileName)) {
if (!firstLine)
sb.AppendLine();
sb.Append(line);
firstLine = false;
// 3: We want at most 3 chunks (item, subitem and tail to throw away)
string[] data = line.Split(new char[0], 3);
ListViewItem item = new ListViewItem() {
Text = data[0]
};
if (data.Length > 1)
item.SubItems.Add(data[1]);
listView1.Items.Add(item);
}
}
finally {
// The file has been scanned, items added; now we a ready to redraw the listView1
listView1.EndUpdate();
}
this.textBox1.Text = text.ToString();
You can use the following.
ReadToEnd does this: Reads all characters from the current position to the end of the stream. You are losing the position of the stream.
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
string line = String.Empty;
StringBuilder sb = new StringBuilder();
// this.textBox1.Text = sr.ReadToEnd(); // remove it, listview working
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(new char[0]);
ListViewItem item = new ListViewItem
{
Text = data[0]
};
item.SubItems.Add(data[1]);
listView1.Items.Add(item);
sb.AppendLine(line);
}
this.textBox1.Text = sb.ToString();
}
You can try this:
string filename = openFileDialog1.FileName;
var lines = File.ReadAllLines(filename);
textBox1.Text = string.Join(Environment.NewLine, lines);
foreach ( string line in lines )
{
var items = line.Split(new char[0]);
if ( items.Length > 0 )
{
var item = new ListViewItem(items[0]);
if ( items.Length > 1 )
item.SubItems.Add(items[1]);
listView1.Items.Add(item);
}
}

Can't move my stream reader to the second column and add the years

I'm really new to visual studio c# I can't seem to add the text file (Stream reader) To my second column and add the years. I tried a few things but this is what I sort of came up with. I tried doing the subitem add but it didn't work for me. I'm just going with what my teacher and the textbook showed but I haven't gotten much luck. The only real problem i'm having is having the stream reader show in the second column rather then the first as i need the first column to add the years.
edit. Sorry yeah whenever i try to type any code to move it to the second column in list view it either makes the txtfile disappear or it doesn't move at all.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<string> Populationsstats = new List<string>();
private void Form1_Load(object sender, EventArgs e)
{
const int SIZE = 7;
const int COLS = 2;
string[] arrLines = new string[SIZE];
int[] values = new int[COLS];
double dblAverage;
double dbllargest;
double dblsmallets;
listView1.GridLines = true;
//listview default settings
listView1.View = View.Details;
listView1.FullRowSelect = true;
//colum header
listView1.Columns.Add("Year", 100);
listView1.Columns.Add("Increase", 120);
//declare a streamreader
//StreamReader inputFile;
StreamReader inputFile = File.OpenText("USPopulation.txt");
//open the file
// inputFile = File.OpenText("USPopulation.txt");
//populate list
while (!inputFile.EndOfStream)
{
Populationsstats.Add(inputFile.ReadLine());
// Populationsstats.Add(int.Parse(inputFile.ReadLine()));
}
//close file
inputFile.Close();
//show items on uspop txt
// listView1.Items.Clear();
dblAverage = 2384; //average equation
listBox1.Items.Add("The Annual Change In Population:" + dblAverage.ToString());
dbllargest = 1955; //largest value
listBox1.Items.Add("The Year with the Greatest Increase:" + dbllargest.ToString());
dblsmallets = 1967; //Smallest value
listBox1.Items.Add("The Year with the Least increase:" + dblsmallets.ToString());
// show items in list view columns
if (Populationsstats.Count != 0)
{
for (int index = 0; index < Populationsstats.Count; index++)
{
ListViewItem cols = new ListViewItem();
listView1.Items.Add(Populationsstats[COLS].ToString());
}
}
}
}
Maybe try to use
string[] readText = File.ReadAllLines(path);
And then get rows you need.

C#: Unable to assign Image to PictureBox image source path from text file in winforms

I'm trying to display image in a PictureBox dynamically. Image source is stored in a text file. When reading the image path from the file it keep showing image error symbol. When I include the path in the code it works.
Text file line sample
F01,Nasi Lemak,RM 2,#"Food\NasiLemak.jpg"
public void readData()
{
try
{
int i = 0;
foreach (string line in File.ReadAllLines("food.txt"))
{
string[] parts = line.Split(',');
foreach (string part in parts)
{
Console.WriteLine("{0}:{1}", i, part);
{
Label LblFId = new Label();
{
//LblFId.AutoSize = true;
LblFId.Size = new System.Drawing.Size(70, 20);
}
Label LblFName = new Label();
{
LblFName.Size = new System.Drawing.Size(70, 20);
}
Label LblFPrice = new Label();
{
LblFPrice.Size = new System.Drawing.Size(70, 20);
}
PictureBox foodPicBox = new PictureBox();
{
foodPicBox.Size = new System.Drawing.Size(200, 200);
foodPicBox.SizeMode = PictureBoxSizeMode.StretchImage;
foodPicBox.BorderStyle = BorderStyle.Fixed3D;
}
Panel fPanel = new Panel();
LblFId.Text = parts[0];
LblFName.Text = parts[1];
LblFPrice.Text = parts[2];
foodPicBox.ImageLocation = parts[3];
fPanel.Controls.Add(LblFId);
fPanel.Controls.Add(LblFName);
fPanel.Controls.Add(LblFPrice);
fPanel.Controls.Add(foodPicBox);
foodFlow.Controls.Add(fPanel);
}
}
i++;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
The problem is in the path from the text file
#"Food\NasiLemak.jpg"
This should be saved like without the # and the "
Food\NasiLemak.jpg
Or you should write more code to remove those symbols like this
foodPicBox.ImageLocation = parts[3].Replace("#", "").Replace("\"", "");
This will remove the samples and your problem would be solved.
You need also to close foreach statment at this point
foreach (string part in parts)
{Console.WriteLine("{0}:{1}", i, part);}

Dynamically Create Controls Based Off Data Returned From Query

I am querying access table and with my data that is returned I need to be able to create controls. Now the problem with my code is (I obviously need to learn about loops better than I do) the code executes exactly as it should it does the 1st foreach loop then moves to the 2nd foreach loop. So I have all the labels - then I have all the text boxes. I need it to be a 1 to 1 relationship. So Label Text box. This is my current code that is not producing the desired outcome. Can someone assist me in tweaking this to produce the desired outcome of a 1 to 1 relationship of label to textbox
System.Collections.Hashtable lookup = new System.Collections.Hashtable();
OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + oName);
olecon.Open();
OleDbCommand command = new OleDbCommand("Query Data Goes Here", olecon);
OleDbCommand command1 = new OleDbCommand("Query Data Goes Here", olecon);
dr = command.ExecuteReader();
while (dr.Read())
{
labelNames.Add(dr[0].ToString());
}
dr.Close();
dr = command1.ExecuteReader();
while (dr.Read())
{
textboxNames.Add(dr[0].ToString());
}
dr.Close();
foreach (string label in labelNames)
{
Label lbl = new Label();
lbl.Name = "lbl_" + index;
lbl.Text = label;
lbl.AutoSize = true;
Form1.Controls.Add(lbl);
index++;
}
foreach (string textbox in textboxNames)
{
TextBox tbx = new TextBox();
tbx.Name = "txt_" + counter;
tbx.AutoSize = true;
Form1.Controls.Add(tbx);
counter++;
}
I don't see any use of textboxNames collection. What you need is, group the two foreach and create label and textbox together and add them to your Form like below
foreach (string label in labelNames)
{
Label lbl = new Label();
lbl.Name = "lbl_" + index;
lbl.Text = label;
lbl.AutoSize = true;
Form1.Controls.Add(lbl);
TextBox tbx = new TextBox();
tbx.Name = "txt_" + index;
tbx.AutoSize = true;
Form1.Controls.Add(tbx);
index++;
}
Rather than doing them as 2 separate foreach loops you could do it in a single for loop, e.g. (assuming labelNames and textboxNames are List<string>):
for (int i = 0; i < labelNames.Count; i++)
{
Label lbl = new Label();
lbl.Name = "lbl_" + labelNames[i];
lbl.Text = labelNames[i];
lbl.AutoSize = true;
Form1.Controls.Add(lbl);
TextBox tbx = new TextBox();
tbx.Name = "txt_" + textboxNames[i];
tbx.AutoSize = true;
Form1.Controls.Add(tbx);
}
Might also be worth checking there are equal numbers of each first as a sanity check:
if (labelNames.Count != textboxNames.Count)
{
//throw exception etc.
}
Replace your two foreach loops with a single for loop that iterates through both lists at the same time.:
for(int i = 0; i < Math.Min(labelNames.Length, textboxNames.Length); i++)
{
Label lbl = new Label();
lbl.Name = "lbl_" + i;
lbl.Text = textboxNames[i];
lbl.AutoSize = true;
Form1.Controls.Add(lbl);
TextBox tbx = new TextBox();
tbx.Name = "txt_" + i;
tbx.AutoSize = true;
Form1.Controls.Add(tbx);
}
The "Math.Min(labelNames.Length, textboxNames.Length)" comparator will make sure the loop stops after whichever list has the fewest entries. I didn't see either of your labelNames or textboxNames collections defined so I'm not sure whether they're arrays or lists or what, so you may need to change "Length" to "Count".

Categories

Resources