Variable item only displaying one line - c#

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();

Related

Displaying delimited text to a listview in 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);
}

Write Specific SubItems to .txt while looping through ListView Control?

My below code first writes an exclamation point (!) delimited Header to a .txt file and then loops through each item and subItem in a ListView Control, placing each record value onto a new line in my .txt file. All the values are needed for user review while in the ListBox, but when writing to the file, I need to only write the fields that are used in the next step, using the .txt file as datasource for MS Word MailMerge document.
Instead of looping through and appending every record field value to my StringBuilder, I need a way to get only the values where the ListView Column Header is the following:
memno
name
address1
address2
address3
sal
fuldate
sys
private void btnMerge_Click(object sender, EventArgs e)
{
try
{
string docLoc = "";
string docSource = "";
StringBuilder sb;
// Change this to the DataSource FilePath
StreamWriter sw = new StreamWriter("C:\\Users\\NAME\\Desktop\\Test2.txt");
string fileHeaderTxt = "memno!name!address1!address2!city!state!zip!old_addr1!old_addr2!old_city!old_state!old_zip!sys!fuldate!sex!lname!sal!address3";
sb = new StringBuilder();
sb.Append(fileHeaderTxt);
sw.WriteLine(sb.ToString());
sb.Clear();
if (lvData.Items.Count > 0)
{
foreach (ListViewItem lvI in lvData.Items)
{
sb = new StringBuilder();
foreach (ListViewItem.ListViewSubItem lvSI in lvI.SubItems)
{
sb.Append(string.Format("{0}!", lvSI.Text));
}
sw.WriteLine(sb.ToString());
}
sw.WriteLine();
}
//sb.Clear();
sw.Close();
MessageBox.Show("Complete");
if (rbPrint.Checked)
{
Print(docLoc, docSource);
}
if (rbCommit.Checked)
{
Commit_NetFYI();
}
}
catch (Exception ex)
{
MessageBox.Show("Source:\t" + ex.Source + "\nMessage: \t" + ex.Message + "\nData:\t" + ex.Data);
}
finally
{
//
}
}
I've been hammering away at this for last couple hours and just can't seem to get it. Anyone have some ideas?
EDIT:
I modified my code using Grammarian's solution, but it seems I am missing something. Each loop iteration writes a line containing all previous looped values, plus the new value.
Rough Example:
Header1!Header2!Header3!Header4
1!2!3!4
1!2!3!4!5!6!7!8
1!2!3!4!5!6!7!8!9!10!11!12
1!2!3!4!5!6!7!8!9!10!11!12!13!14!15!16
etc.
Here is my current code:
private void btnMerge_Click(object sender, EventArgs e)
{
try
{
string docLoc = "";
string docSource = "";
StringBuilder sb;
// Change this to the DataSource FilePath
StreamWriter sw = new StreamWriter("C:\\Users\\NAME\\Desktop\\Test2.txt");
string fileHeaderTxt = "memno!name!address1!address2!city!state!zip!old_addr1!old_addr2!old_city!old_state!old_zip!sys!fuldate!sex!lname!sal!address3";
sb = new StringBuilder();
sb.Append(fileHeaderTxt);
sw.WriteLine(sb.ToString());
sb.Clear();
if (lvData.Items.Count > 0)
{
foreach (ListViewItem lvI in lvData.Items)
{
var indices = new int[] { 0, 1, 2, 3, 12, 13, 16, 17 };
foreach (int i in indices)
{
sb.Append(string.Format("{0}!", lvI.SubItems[i].Text));
}
sw.WriteLine(sb.ToString());
sb.Clear();
}
sw.WriteLine();
}
}
}
EDIT2:
Got it, wasn't clearing out my stringBuilder object after each time through my first loop. Edited code above to reflect working code.
Rather than always just iterating all subitems, make an array of subitem indices in the order you want, and iterate the indices.
var indices = new [] { 0, 1, 2, 4, 9 }; // whatever you want
foreach (int i in indices)
{
sb.Append(string.Format("{0}!", lvI.SubItems[i].Text));
}

File contents filtering

I'm trying to develop an application which will take the data from a datagrid and based on a drop down menu choice return a csv file with only the selected client . My code is shown below , This links to a previous question I posted howeever I am still getting no values back and I really need to sort this out so I'm wondering if anyone can either see were i'm going wrong or else provide alternatives
//Master inventory export
private void ExportClass_Click(object sender, EventArgs e)
{
StringBuilder str = new StringBuilder();
objSqlCommands2 = new SqlCommands("MasterInventory", "ClientName");
string strString = str.ToString();
string Filepath = txtSaveShareClass.Text.ToString();
str.Append("ISIN ,FundName,Status,Share CCY,Benchmark,NAV Freq,CLASSCODE,SIMULATION,HEDGED,FUNDCCY");
StringManipulation sm = new StringManipulation();
foreach (DataRow dr in this.CalcDataSet.MasterInventory)
{
foreach (object field in dr.ItemArray)
{
str.Append(field.ToString() + ",");
}
str.Replace(",", "\n", str.Length - 1, 1);
}
try
{
System.IO.File.WriteAllText(Filepath, str.ToString());
}
catch (Exception ex)
{
MessageBox.Show("Write Error :" + ex.Message);
}
List<string[]> lsClientList = objStringManipulation.parseCSV(Filepath,cmbClientList .Text.ToCharArray());
foreach (string[] laClient in lsClientList)
{
sm.parseCSV2(Filepath, cmbClientList.Text.ToCharArray());
List<string[]> newFoo = lsClientList.Where(x => x.Contains(cmbClientList.Text)).ToList();
List<string[]> Results = sm.parseCSV2(Filepath, cmbClientList.Text.ToCharArray()).Where(x => x.Contains(cmbClientList.Text)).ToList();
//Refreshs the Client table on display from the
System.IO.File.WriteAllText(Filepath, Results.ToString());
}
this.TableAdapter.Fill(this.CalcDataSet.MasterInventory);
dataGridView2.Update();
}
If all of your variables are filling properly and your Results list contains the data that you expect, then the problem is with your WriteAllText call. You have:
System.IO.File.WriteAllText(Filepath, Results.ToString());
That is not going to produce the output that you seem to expect. It will likely just give you the class name.
Results is a List<string[]>. If you want to output that as a CSV, then you have to enumerate it:
using (var outfile = new StreamWriter(Filepath))
{
foreach (var line in Results)
{
StringBuilder sb = new StringBuilder();
foreach (var field in line)
{
sb.Append(field + ",");
}
sb.Length = sb.Length -1;
outfile.WriteLine(sb.ToString());
}
}

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);
}

Null reference exception in foreach (string var in Request.QueryString)

I tried to find a solution for this question, but with no success...
I tried to remove .ToString() from Request.QueryString[var] and to add an if control
at the beginning like this
if Request.QueryString.HasKeys()) {
foreach (string var in Request.QueryString)
{.........
.............
}
but nothing....
The complete code is
string[] array_split_item = new string[] {"<script", "</script>", "‘", "’" };
int pos = 0;
string strReq = "";
foreach (string var in Request.QueryString)
{
foreach (string strItem in array_split_item)
{
strReq = Request.QueryString[var].ToString();
pos = strReq.ToLower().IndexOf(strItem.ToLower()) + 1;
if (pos > 0)
{
Response.Write("Some Text");
Response.End();
}
}
}
Why this exception?
Thanks
you can't foreach through Request.QueryString like that.
Try this (not tested)
foreach (string KEY in Request.QueryString.Keys)
{
string value = Request.QueryString[KEY]; //already a string by design, no need to ToString() it
// ... use value for whatever you need
}
EDIT:
visual studio 2008 builds this fine (pasted into the page_load method of an ASPX page to try it); Visual Studio 2010 SP1 doesn't complain either upoon building.
string[] array_split_item = new string[] { "<script", "</script>", "‘", "’" };
int pos = 0;
string strReq = "";
foreach (string var in Request.QueryString.Keys)
{
foreach (string strItem in array_split_item)
{
strReq = Request.QueryString[var].ToString();
pos = strReq.ToLower().IndexOf(strItem.ToLower()) + 1;
if (pos > 0)
{
Response.Write("Some Text");
Response.End();
}
}
}
There must be something wrong somewhere else in the code i think.
I beleive it may be because you're using the value of a key in QueryString to access a value.
Try changing the line strReq = Request.QueryString[var].ToString(); to
strReq = var.ToString();
You should use Request.QueryString.Keys to loop on the QueryString:
foreach (string key in Request.QueryString.Keys)
{
string value = Request.QueryString[key];
if (!String.IsNullOrEmpty(value))
{
//do work
}
}
You are naming your string var which is also a type. Replace var with another name.
foreach (string text in Request.QueryString.Keys)
.....
strReq = Request.QueryString[text].ToString();

Categories