Displaying delimited text to a listview in c# - c#

I have a text file(location stored in destination in program) I want to read the data line by line and write it to the list view. List View has three columns.
TextFile
Hello*How are you*I am
olleh*uoy era woh*ma I
Output in list view
Hello | How are you | I am
olleh| uoy era woh |ma I
File Name:Program.cs
public void read(string destination)
{
StreamReader sw = File.OpenText(destination);
string s = "";
while ((s = sw.ReadLine()) != null)
{
string[] words = s.Split('*');
foreach(string word in words)
{
// i have no idea how to send it to the list view
}
}
sw.Close();
}
File Name: Form1.cs
private void button1_Click(object sender, EventArgs e)
{
ListViewItem lvi = new ListViewItem();
lvi.SubItems.Add();
lvi.SubItems.Add();
listview1.Items.Add(li);
}

Add your words to list
List<string> wordslist=new List<string>();//global declaration
while ((s = sw.ReadLine()) != null)
{
string[] words = s.Split('*');
foreach(string word in words)
{
wordslist.Add(word);
}
}
then loop to fill data in list view
for(int i=0;i<wordslist.Count-2;i+=3)
{
lvi.SubItems.Add(i);
lvi.SubItems.Add(i+1);
lvi.SubItems.Add(i+2);
listview1.Items.Add(li);
}

Related

C#: Populate Combobox with single column in CSV

I have a csv file with multiple columns, "PROJECT NAME", "PROJECT BUILD". I am trying to populate comobobox with Project Name column only.
Project name column might have multiple repeated names but repeated names should only appear once in combobox as an option to select. For example: in column 1, under "Project Name", Toyota is listed 4 times and Honda is listed 8 Times. Combobox will have 2 things, Toyota and Honda.
Here is my code so far:
// Wehn Form Loads___________________________________________________________________________________________________
public void OnLoad(object sender, RoutedEventArgs e)
{
StreamReader sr = new StreamReader(path);
string column = sr.ReadToEnd();
string[] eachColumn = column.Split(',');
foreach (string s in eachColumn)
{
Project_Name_Combobox.Items.Add(s);
}
}
The current code gets me the entire csv content (row and column) separated by "," listed under combo box. :(. Any help is apricated.
You have to separate out the rows and columns from csv and store whatever you need separately like below.
public void OnLoad(object sender, RoutedEventArgs e)
{
StreamReader sr = new StreamReader(path);
List<string> ProjectNames = new List<string>();
int lineNumber = 1;
while (!sr.EndOfStream)
{
var EachRow = sr.ReadLine();
var Columns= EachRow.Split(',');
if(lineNumber != 1){
ProjectNames.Add(Columns[0]);
}
lineNumber++;
}
ProjectNames = ProjectNames.Distinct().ToList();
foreach(var projectName in ProjectNames){
Project_Name_Combobox.Items.Add(projectName);
}
}

Variable item only displaying one line

For each of the lines with the specific keyword, I want to print it to a TextBox.
But once I got it to read the text file and select the lines with the keyword and add it to a List, it only displays the first line of the list.
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var client = new WebClient();
var text = client.DownloadString("https://foo.com/list");
File.WriteAllText("C:/ProgramData/oof.txt", text);
string searchKeyword = "Name";
string fileName = "C:/ProgramData/oof.txt";
string[] textLines = File.ReadAllLines(fileName);
List<string> results = new List<string>();
foreach (string line in textLines)
{
if (line.Contains(searchKeyword))
{
results.Add(line);
}
foreach (var item in results)
{
richTextBox1.Text = item;
}
}
}
your loop at the end just sets the text to the last item.
foreach (var item in results)
{
richTextBox1.Text = item;
}
not clear what you want but how about this.
var sb = new StringBuilder();
foreach (var item in results)
{
sb.Append(item);
sb.Append " ";
}
richTextBox1.Text = sb.ToString();

How to read a text file's data vertically or column wise

How can we read a text file column by column.
Check my new code: I can read the data row-wise using text.split (' ')
But how can be the file read as column wise? Lets assume that a file contains number of rows and columns but I was able to read the data/value horizontally. The code you see that below that's what I could execute!
SEE THE CODE BELOW:-
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string text = "";
text = textBox1.Text;
string[] arr = text.Split(' ');
textBox2.Text = arr[5];
textBox3.Text = arr[8];
}
private void button3_Click(object sender, EventArgs e)
{
string file_name = "c:\\Excel\\count.txt";
string txtline = "";
System.IO.StreamReader objreader;
objreader = new System.IO.StreamReader(file_name);
do
{
txtline = txtline + objreader.ReadLine() + "\r\n";
txtline = txtline + objreader.ReadToEnd() + "";
this.textBox1.Text = "subzihut";
}
while (objreader.Peek() != -1);
textBox1.Text = txtline;
objreader.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox4.Text = textBox2.Text + " " + textBox3.Text;
}
}
}
A textfile contains a sequence of characters, delimited by newline characters and probably other characters which are used as delimiters (usually a comma or a semiciolon).
When you read a file you simply read this stream of characters. There are helper functions which read such a file line-by-line (using the newline character as a delimiter).
In plain .Net there are no methods which read column-by-column.
So you should:
read the file line by line
split each line into fields/columns using string.Split() at the separator character(s)
access only the columns of interest
You can simply read the file line by line, splitt the lines and do whatever you want.
var lines = File.ReadLines(#"c:\yourfile.txt");
foreach(var line in lines)
{
var values = line.Split(' ');
}
public string getColumnString(int columnNumber){
string[] lines = System.IO.ReadAllLines(#"C:\inputfile.txt");
string stringTobeDisplayed = string.Empty;
foreach(string line in lines) {
if(columnNumber == -1){ //when column number is sent as -1 then read full line
stringTobeDisplayed += line +"\n"
}
else{ //else read only the column required
string [] words = line.Split();
stringTobeDisplayed += word[columnNumber] +"\n"
}
}
return stringTobeDisplayed;
}
Maybe this will help you:
public static void ReadFile(string path)
{
List<string> Col1 = new List<string>();
List<string> Col2 = new List<string>();
List<string> Col3 = new List<string>();
using (StreamReader sr = new StreamReader(path))
{
while (sr.EndOfStream)
{
string header = sr.ReadLine();
var values = header.Split(' ');
Col1.Add(values[0]);
Col2.Add(values[1]);
Col3.Add(values[2]);
}
}
}
It's true that sometimes you just don't know where to start. Here are some pointers.
You'll have to read the whole file in, probably using something like a StreamReader.
You can parse the first row into column names. Use StreamReader.ReadLine() to get the first line and then do some simple string parsing on it.
You'll want to create some kind of class/object to store and access your data.
Once you have column names, continue to parse the following lines into the proper arrays.
Some here's a rough idea
using(StreamReader sr = new StreamReadeR("C:\\my\\file\\location\\text.csv"))
{
string header = sr.ReadLine();
List<string> HeaderColumns = new List<string>(header.split(" ", StringSplitOptions.RemoveEmptyEntires));
myModelClass.Header = HeaderColumns;
etc...
You might also consider making some kind of dictionary to access columns by header name and index.

Logical error in writing data in a text file in one column

My Usecase is to read data from a textfile by browsing to the location of the file containing the data to be quoted.the data from the file is save in a list. i use arraylist to get the data and loop through the arraylist and concatenate each string then create output file to store the data in single column as demostrated below
Example of a string:
20050000
40223120
40006523
sample out put:
'20050000',
'40223120',
'40006523'
But my code is currently displaying the output in the format:
'20050000'20050000,
'40223120'20050000,
'40006523'40006523
Pls help.
public List<string> list()
{
List<string> Get_Receiptlist = new List<string>();
String ReceiptNo;
openFileDialog1.ShowDialog();
string name_of_Textfile = openFileDialog1.FileName;
try
{
StreamReader sr = new StreamReader(name_of_Textfile);
{
while ((ReceiptNo = sr.ReadLine()) != null)
{
Get_Receiptlist.Add(ReceiptNo);
} // end while
MessageBox.Show("Record saved in the Data list");// just for testing purpose.
}// end StreamReader
}
catch (Exception err)
{
MessageBox.Show("Cannot read data from file");
}
return Get_Receiptlist;
}
private void button2_Click(object sender, EventArgs e)
{
string single_quotation = "'";
string comma = ",";
string paths = #"C:\Users\sample\Desktop\FileStream\Output.txt";
if (!File.Exists(paths))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(paths))
{
string[] receipt = list().ToArray();
foreach (string rec in receipt)
{
string quoted_receipt = single_quotation + rec + single_quotation + rec + comma;
sw.WriteLine(quoted_receipt);
sw.WriteLine(Environment.NewLine);
}//foreach
sw.Close();
MessageBox.Show("Finish processing File");
}//end using
}// end if
}
In your method button2_Click you have bad loop:
string[] receipt = list().ToArray();
foreach (string rec in receipt)
{
string quoted_receipt = single_quotation + rec + single_quotation + rec + comma;
sw.WriteLine(quoted_receipt);
sw.WriteLine(Environment.NewLine);
}//foreach
First I'm not even sure its Java ... but if it was Java, then I would replace this fragment with this:
List<String> values = list();
for (int i = 0; i < values.size(); i++)
{
String rec = values.get(i);
StringBuilder quoted_receipt = new StringBuilder();
if (i > 0)
{
// add comma only if the first iteration already passed
quoted_receipt.append(comma);
}
quoted_receipt.append(single_quotation).append(rec).append(single_quotation);
sw.WriteLine(quoted_receipt.toString());
sw.WriteLine(Environment.NewLine);
}

Changing a part of text line in a file on mouse doubleclick by comparing it with a value

I have a file-message.txt that contains raw data, my application reads the file, parses it and displays the data accordingly in the listview. The raw data contains a word called REC UNREAD meaning the record is unread. So for the first time when message is read it is UNREAD and I display such messages in bold. After I read it(Using doubleclick event) the word REC UNREAD should be changed to REC READ. This is what I have I tried, not working though
private void lvwMessages_MouseDoubleClick_1(object sender, MouseEventArgs e)
{
try
{
ListViewItem item = lvwMessages.SelectedItems[0];
if(item.Font.Bold)
{
lvwMessages.SelectedItems[0].Font = new Font(lvwMessages.Font, FontStyle.Regular);
string tfile = File.ReadAllText("C:\\message.txt");
string m1 = lvwMessages.SelectedItems[0].SubItems[1].Text;
string m2 = lvwMessages.SelectedItems[0].SubItems[2].Text;
//No idea how to go forward from here
This is a sample line in my text file:
+CMGL: 2,"REC UNREAD","+919030665834","","2012/08/10 17:04:15+22"
sample message
In simple words I should be able to search for the line containing m1 and m2(as in the code) and replace the REC UNREAD with REC READ.
This should solve your problem--
ListViewItem item = lvwMessages.SelectedItems[0];
if(item.Font.Bold)
{
lvwMessages.SelectedItems[0].Font = new Font(lvwMessages.Font, FontStyle.Regular);
string tfile = File.ReadAllText("C:\\message.txt");
string m1 = lvwMessages.SelectedItems[0].SubItems[1].Text;
string m2 = lvwMessages.SelectedItems[0].SubItems[2].Text;
string line = string.Empty;
string nfile= "";
using (StreamReader sr = new StreamReader("C:\\message.txt"))
{
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(m2))
{
string pline = line;
string result = line.Replace("REC UNREAD", "REC READ");
nfile= tfile.Replace(pline, result);
}
}
sr.Close();
}
StreamWriter sw = new StreamWriter("C:\\message.txt");
{
sw.Write(nfile);
}
sw.Close();
}
you can try with this code based on IndexOf and Replace
string line = string.Empty;
using (StreamReader sr = new StreamReader("C:\\message.txt"))
{
while ((line = sr.ReadLine()) != null)
{
if (line.IndexOf(m1) > 0 &&
line.IndexOf(m2) )
{
var result = line.Replace(m2, "READ");
}
}
}

Categories