C# Loadl List into textbox WinForms - c#

I have a problem when I try to display the list into the textbox. It only displays the last line from the list.txt file. I think for each new line it overwrites the first line from the textbox all the time ? thus showing only the last line from the file ?
what is it I need to think of to get it right ?
private void Form1_Load(object sender, EventArgs e)
{
const string f = "list.txt";
List<string> myList = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
myList.Add(line);
}
}
foreach (string s in myList)
{
textBox1.Text = string.Join(Environment.NewLine, s);
}
}

Instead of this:
foreach (string s in myList)
{
textBox1.Text = string.Join(Environment.NewLine, s);
}
Try:
textBox1.Text = string.Join(Environment.NewLine, myList);
And also make sure multiline property of textbox1 is set to true.

Because every time, you assign directly to the Text property which will remove the previous one . Here is the fix . Make Multiline of textbox true.
private void Form1_Load(object sender, EventArgs e)
{
const string f = "list.txt";
List<string> myList = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
myList.Add(line);
}
}
var listString = new StringBuilder()
foreach (string s in myList)
{
listString.Append(Environment.Newline)
listString.Append(s);
}
textBox1.Text = listString.ToString();
}

Based on my comment you can do this in one simple line by eliminating the foreach loop
textBox1.Text = string.Join(Environment.NewLine, myList.ToArray());
or just use the myList works the same
textBox1.Text = string.Join(Environment.NewLine, myList);

Related

How do I delete or modify a line in a text file if it matches the string in my combo box C#

So I have a combo box that contains a list of trainees that is imported from a textfile (each trainee occupies a line in the textfile) and I have 3 buttons, add (adds a new trainee to the file and combobox), delete(Supposed to delete the specific line in the file containing the combobox selected item) and a modify button (supposed to overwrite a new trainee in the file at the same line that contains the combobox selected item), my add button works fine, idk how to modify or delete lines in a file.
I have no idea how to work this around as I'm new to working with files
here's my code
private void form1_Load(object sender, EventArgs e)
{
FileStream fs = new FileStream("trainee.txt", FileMode.Open);
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(fs))
{
string line;
while ((line = r.ReadLine()) != null)
{
comboBox1.Items.Add(line);
}
}
fs.Close();
}
private void deleteButton_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Choose a trainee to delete.", "Error !");
}
else
{
string selection = comboBox1.SelectedItem.ToString();
FileStream fs = new FileStream("stagiaire.txt", FileMode.Open);
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(fs))
{
string line;
while ((line = r.ReadLine()) == selection)
{
}
}
fs.Close();
private void button2_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedItem == null)
{
MessageBox.Show("Choose a trainee to modify.", "Error !");
}
else
{
string selection = comboBox1.SelectedItem.ToString();
FileStream fs = new FileStream("trainee.txt", FileMode.Open);
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(fs))
{
string line;
if ((line = r.ReadLine()) == selection)
{
Trainee stg = new Trainee();
stg.name = textBox1.Text;
stg.nickname = textBox2.Text;
stg.training_days = int.Parse(textBox3.Text);
addtrainee(stg);
comboBox1.Items.Add(stg);
}
}
fs.Close();
}
You may be working too hard, the List you have is working for you here. Whenever you need to output it, just write the whole list. When you need to manipulate the entries in it (elements), use the collection methods like Find, Contains, Add, Remove, others see (https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netframework-4.7.2#methods)
You can shortcut you file access too, use the framework:
var fileLines = File.ReadLines("c:/temp/yourfile.txt");
No using and StreamReader/Writer needed, depending on your environment too I guess.
So you have your input as string and List<string> so you could do if (lines.Contains(testString)) for example.
Can provide more sample code if it helps.

Add List<string> to DataGridView Rows

I am new to using the DataGridView component, I've used it once before and have managed to complete this exact task but I forgot how I achieved it.
Basically I would like to read the values from a text file which is formatted like so:
line 1,
line 2,
line 3
Here is the code I currently have:
List<string> tokens = new List<string>();
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
string[] lines = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach (var line in lines)
{
using (StreamReader sr = new StreamReader(Path.GetFullPath(line)))
{
var l = sr.ReadLine();
string[] data;
while (l != null)
{
data = l.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
l = sr.ReadLine();
tokens.Add(l);
}
}
}
for (int i = 0; i < tokens.Count - 1; i++)
{
dataGridView1.Rows[i].Cells[0].Selected = true;
dataGridView1.CurrentCell.Value = tokens[i];
}
}
The current code results in the line 2 being added to the datagridview only, with nothing else.
I would like to add each line into the first column of each row, depending on how many lines are in the text file.
Hopefully this makes sense, thanks a lot!
You can try this:
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
dataGridView1.Columns.Add("Value", "Value");
var files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach ( var file in files )
{
var lines = File.ReadAllLines(Path.GetFullPath(file));
foreach ( string line in lines )
dataGridView1.Rows.Add(line.TrimEnd(','));
}
}
private void dataGridView1_DragEnter(object sender, DragEventArgs e)
{
if ( e.Data.GetDataPresent(DataFormats.FileDrop) )
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}

search a textfile with a textbox

I have a textbox that I want to use to autosearch my text file and display the results in the listbox. the listbox already contains the first item of each line in the text file, so I basically want to search using only the first item of every line in the text file.
The code I currently have does nothing.
private void custsearchbox_TextChanged(object sender, EventArgs e)
{
string[] autosource = File.ReadAllLines(#"data\Suppliers.txt");
for (int g = 0; g < autosource.Length; g++)
{
custsearchbox.AutoCompleteCustomSource.Add(autosource[g]);
}
custsearchbox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
}
I want to type the first item in my text box and search my listbox, as I enter my text I want the list to filter out the items that does not match. Please help me achieve this.
I tried this:
private void supsearchtxt_TextChanged(object sender, EventArgs e)
{
listsup.Items.Clear();
Supfile = System.AppDomain.CurrentDomain.BaseDirectory + "data\\Suppliers.txt";
List<string> proName = new List<string>();
using (StreamReader rdr = new StreamReader(Supfile))
{
string line;
while ((line = rdr.ReadLine()) != null)
{
if (line.Contains(supsearchtxt.Text))
{
string[] val = line.Split(',');
listsup.Items.Add(val[0]);
}
}
}
}
and it works great.

Extracting Number from a Text File in C# Windows Form

I have written a code for extracting number from a text file using a windows From. Problem is that, Output Occurs in a partial way. Either the First Line is Printing or the Last Line. I want all the line that is containing the number
(i.e) If the text file contains,
Auto 2017
Mech 2056
CSE 2016
I want only those 2017, 2056, 2016 to be printed.
Here is the code:
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
StreamReader sr = new StreamReader(infile);
string allDetails = File.ReadAllText(infile);
string result = Regex.Match(allDetails, #"\d+").Value;
richTextBox1.Text = result.ToString();
}
You are try to grab numeric value. Regex.Matches Will help you to solve your problem.
Below is simplified code.
private void button1_Click(object sender, EventArgs e)
{
string filedetails = File.ReadAllText(textBox1.Text);
var regexCollection = Regex.Matches(filedetails, #"\d+");
foreach (Match rc in regexCollection)
richTextBox1.AppendText(rc.Value + ",");
}
You can do this way, if you want output 2017,2056,2016
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
string[] lines = System.IO.File.ReadAllLines(infile);
string temp = "";
int i = 0;
foreach (string line in lines)
{
string result = Regex.Match(line, #"\d+").Value;
if (i == 0)
{
temp = result;
}
else
{
temp = temp + "," + result;
}
i++;
}
richTextBox1.Text = temp;
}
or if you want single value 2017 2056 2016 then
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
string[] lines = System.IO.File.ReadAllLines(infile);
foreach (string line in lines)
{
string result = Regex.Match(line, #"\d+").Value;
richTextBox1.Text = result ;
}
}
You need to use the method. Regex.Matches. Matches method searches the specified input string for all occurrences of a regular expression.
Match method returns the first match only, Subsequent matches need to be retrieved.
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
StreamReader sr = new StreamReader(infile);
string allDetails = File.ReadAllText(infile);
var regexMatchCollection = Regex.Matches(allDetails, #"\d+");
foreach(Match mc in regexMatchCollection)
{
richTextBox1.AppendText(mc.Value);
richTextBox1.AppendText(",");
}
}
test.txt has
Auto 2017
Mech 2056
CSE 2016
in the following program File.ReadAllLines will store every line in a string array separately.Then we will use foreach loop to read single line at a time and store the extracted numbers in list e.g 2017 and finally with string.Join we will join the array and separate each word with "," and save it in string
List<string> list = new List<string>();
var textfile = File.ReadAllLines(#"D:\test.txt");
foreach (var line in textfile)
{
string result = Regex.Match(line, #"\d+").Value;
list.Add(result);
}
string numbers = string.Join(",",list.ToArray());
the output value will be
2017,2056,2016
private void button1_Click(object sender, EventArgs e)
{
string infile = textBox1.Text;
StreamReader sr = new StreamReader(infile);
string allDetails = File.ReadAllText(infile);
string result = string.Empty;
foreach (var item in Regex.Matches(allDetails, #"\d+"))
{
result = result + item.ToString() + ",";
}
richTextBox1.Text = result.TrimEnd(',');
}
Without using Regex,below is the simplified code
private void button1_Click(object sender, EventArgs e)
{
StringBuilder numbers = new StringBuilder();
string allDetails = File.ReadAllText(textBox1.Text);
foreach(string word in allDetails.Split(' '))
{
int number;
if(int.TryParse(word, out number))
{
numbers.Append(number);
numbers.Append(",");
}
}
richTextBox1.Text = numbers.Trim(',');
}
static void Main(string[] args)
{
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\admin\Desktop\ConsoleApplication1\ConsoleApplication1\txtFile.txt");
List<string> Codelst = new List<string>();
foreach (var item in lines)
{
var a= Regex.Match(item, #"\d+").Value;
Codelst .Add(a);
}
var r = Codelst;
}
Output is like this:

Trying to populate textbox and listview from txt file

I'm able to save the textbox text and the listview items to a txt file properly by using:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter writer = new StreamWriter(saveFileDialog1.FileName))
{
//writer.WriteLine(accountText.Text);
writer.WriteLine(accountText.Text);
if (transactionList.Items.Count > 0)
{
foreach (ListViewItem item in transactionList.Items)
{
StringBuilder newString = new StringBuilder();
foreach (ListViewItem.ListViewSubItem listSub in item.SubItems)
{
newString.Append(string.Format("{0}\t", listSub.Text));
}
writer.WriteLine(newString.ToString());
}
writer.WriteLine();
}
}
}
}
However, I'm only able to load the textbox and can't seem to get the listview to populate. Here's what I have for that so far:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
accountText.Text = reader.ReadLine();
if (transactionList.Items.Count == 0)
{
foreach (ListViewItem item in transactionList.Items)
{
StringBuilder myString = new StringBuilder();
foreach (ListViewItem.ListViewSubItem listSub in item.SubItems)
{
myString.Append(string.Format("{0}\t", listSub.Text));
}
reader.Read();
}
reader.ReadToEnd();
}
}
}
}
Any tips would be appreciated.
You just need to split string by '\t' character, it will return string[]. Then just add these array items to listview.
string[] items = reader.ReadLine().Split('\t');
foreach (var item in items)
{
var listViewItem = new ListViewItem(item);
transactionList.Items.Add(listViewItem);
}
As far as I can tell you're not putting the string into the ListView.
You will want to to do something like this:
foreach (ListViewItem.ListViewSubItem listSub in item.SubItems)
{
myString.Append(string.Format("{0}\t", listSub.Text));
listSub.Text = myString.ToString();
}
You need to reverse all your actions while reading
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
accountText.Text = reader.ReadLine();
while(!reader.EndOfStream)
{
var myString = reader.ReadLine();
var subitems = myString.Split("\t");
// Create ListItem and assign subItems here...
transactionList.Items.Add(new ListviewItem(subitems));
}
}
}
}
}

Categories

Resources