How to get a Listbox to read to a Listbox - c#

I am trying to open any selected textfile and have the text input be sent to a listbox... Originally I wrote this code for a textbox which worked great now that I am converting it to a listbox it doesnt seem to work so much. I left the default item names in order for better understanding of what is going on.
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label1.Text = openFileDialog1.FileName;
listBox1.Items.Add = File.ReadAllText(label1.Text);
}
}

listBox1.Items.AddRange(File.ReadAllLines(label1.Text));

Try this :
listBox1.Items.AddRange(File.ReadLines(label1.Text).ToArray());

.Add() is a method and you are treating it like a property.
Try this code instead:
listBox1.Items.Add(File.ReadAllText(label1.text));

string[] lines = File.ReadLines("SomeFile.txt").ToArray();
foreach (var line in lines)
{
listBox1.Items.Add(line);
}

private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label1.Text = openFileDialog1.FileName;
//till here the same
//open filestream
System.IO.StreamReader file = new System.IO.StreamReader(openFileDialog1.FileName);
//loop trough lines
while ((line = file.ReadLine()) != null)
{
//add line to listbox
listBox1.Items.Add ( line);
}
}
}

Related

How can i count the words from a richtextbox

I want to make a program that counts as example the word "Me" from a richtextbox. How is this possible in c#. The code that i already have is that it loads a textfile.
private void button1_Click(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
string strfilename = openFileDialog1.FileName;
string filetext = File.ReadAllText(strfilename);
richTextBox1.Text = filetext;
textBox1.Text = openFileDialog1.FileName;
richTextBox1.LoadFile(#"C:\Users\Administrator\Documents\School\C#\DEEL 2\HW5\5.3 opdracht1\Sonnet 14.txt", RichTextBoxStreamType.PlainText);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
}
If you want to use LINQ, you can do it pretty easily. Simply split the text on whitespaces, and then filter the array for words matching what you want. Here's a sample:
string search = "Me";
int count = richTextBox1.Text.Split(' ').Where(word => word == search).Count();
Separete all the words and after that you can do whatever you want
//Variable to store your count
int n = 0;
string stringToCompare = "Me";
string[] data = richTextBox1.Text.Split(' ');
for(int i=0;i<data.Length;i++)
{
if(data[i]==stringToCompare )
n++;
}
Console.WriteLine($"Word {stringToCompare } has appeared {n} times");
If you dont want case sensitive try something like
if(data[i].ToUpper() == stringToCompare.ToUpper() )
n++;

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.

Promblemas to send to call my method to a button

I am learning to program in C # so my question is how to call the method from the button3
Look for information on the web but it is not very clear to me why I turn to this site
private void button3_Click_1(object sender, EventArgs e)
{
}
private void export2File(ListView lv, string splitter)
{
string filename = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "SaveFileDialog Export2File";
sfd.Filter = "Text File (.txt) | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
filename = sfd.FileName.ToString();
if (filename != "")
{
using (StreamWriter sw = new StreamWriter(filename))
{
foreach (ListViewItem item in lv.Items)
{
sw.WriteLine("{0}{1}{2}", item.SubItems[0].Text, splitter, item.SubItems[1].Text);
}
}
}
}
}
private void button3_Click_1(object sender, EventArgs e)
{
ListView listView1 = new ListView();
string splitter = ",";
export2File(listview1, splitter);
}
You need to pass a reference to the ListView on your Form, and the desired "splitter" into the method. Assuming listView1 and a comma:
private void button3_Click_1(object sender, EventArgs e)
{
export2File(listView1, ",");
}

Remove duplicates not working

Hi can i know why this code not working, it's working but it will also remove non duplicates entry and for some lists it will throw some error
ex:
This list working but it will also remove http://test1.com
http://test.com
http://test.com
http://test1.com
http://1test.com
And with this lists will throw this "System.ArgumentNullException was unhandled" error
http://test.com
http://test.com
http://test1.com
http://1test.com
http://etest.com
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog buka = new OpenFileDialog();
buka.InitialDirectory = "";
buka.Filter = "Text files(*.txt)|*.txt|All files (*.*)|*.*";
buka.FilterIndex = 2;
buka.RestoreDirectory = true;
buka.Title = "Cari";
buka.ShowDialog();
string bukafile = buka.FileName;
if (!String.IsNullOrEmpty(bukafile))
{
StreamReader isiFile = File.OpenText(bukafile);
while (isiFile.Peek() != -1)
{
if (!listBox1.Items.Contains(isiFile.ReadLine()))
{
listBox1.Items.Add(isiFile.ReadLine());
}
}
isiFile.Close();
}
}
You should cache the line from isiFile.ReadLine() so you compare the same line as you're adding.
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog buka = new OpenFileDialog();
buka.InitialDirectory = "";
buka.Filter = "Text files(*.txt)|*.txt|All files (*.*)|*.*";
buka.FilterIndex = 2;
buka.RestoreDirectory = true;
buka.Title = "Cari";
buka.ShowDialog();
string bukafile = buka.FileName;
if (!String.IsNullOrEmpty(bukafile))
{
StreamReader isiFile = File.OpenText(bukafile);
while (isiFile.Peek() != -1)
{
// use local variable here
string line = isiFile.ReadLine();
if (!listBox1.Items.Contains(line))
{
listBox1.Items.Add(line);
}
}
isiFile.Close();
}
}
If you don't have a very huge file you could replace a lot of your code using
var lines = File.ReadLines(bukafile).Distinct();
listBox1.DataSource = lines.ToList();
You're reading two lines, one for each ReadLine() call. You use the first line to do the .Contains check, and the second line to add to the listbox. These two lines aren't related to each other in any way.
So for the first list, you first check if http://test.com, the first line, is in the listbox. It isn't, so you read the next line, coincidentally also http://test.com, and add that to the listbox. Then, you check if http://test1.com is in the listbox, find that it isn't, and then proceed to add http://1test.com to the listbox.
For the second list, you have an odd number of entries, so the final call to ReadLine returns, I'm guessing, null, which you can't add to the listbox.
The fix is
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog buka = new OpenFileDialog();
buka.InitialDirectory = "";
buka.Filter = "Text files(*.txt)|*.txt|All files (*.*)|*.*";
buka.FilterIndex = 2;
buka.RestoreDirectory = true;
buka.Title = "Cari";
buka.ShowDialog();
string bukafile = buka.FileName;
if (!String.IsNullOrEmpty(bukafile))
{
StreamReader isiFile = File.OpenText(bukafile);
while (isiFile.Peek() != -1)
{
string line = isiFile.ReadLine();
if (!listBox1.Items.Contains(line))
{
listBox1.Items.Add(line);
}
}
isiFile.Close();
}
}

C# ListBox Selected Item Null Exception

The user can click an item in a ListBox as follows:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox2.Clear();
listBox2.Items.Clear();
string[] p =
Directory.GetFiles(
textBoxDir.Text,
listBox1.SelectedItem.ToString(),
SearchOption.AllDirectories);
foreach (string open in p)
......
}
All is fine. However if the user clicks on an empty space in the ListBox, it displays the following error:
System.NullReferenceException
This is because of this line of code:
string[] p =
Directory.GetFiles(
textBoxDir.Text,
listBox1.SelectedItem.ToString(),
SearchOption.AllDirectories);
Does anyone have a clever work around? Or suggest an aalternative to my code?
The workaround is to check for a null value, and exit early.
if (listBox1.SelectedItem == null)
{
return;
}
This avoids the nesting introduced by the other answers, which makes the code less readable.
You can check SelectedIndex before that line:
if(listBox2.SelectedIndex < 0)
return;
How about doing a
if(listBox1.SelectedItem != null){
// ... do your work with listBox1.SelectedItem here
}
that should prevent that error from happening.
How about
if (listBox1.SelectedItem != null)
{
string[] p = Directory.GetFiles(textBoxDir.Text, listBox1.SelectedItem.ToString(), SearchOption.AllDirectories);
}
Full Code
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
textBox2.Clear();
listBox2.Items.Clear();
string[] p = Directory.GetFiles(textBoxDir.Text, listBox1.SelectedItem.ToString(), SearchOption.AllDirectories);
foreach (string open in p)
...... }
}
}
just check first if listbox1.SelectedItem is empty or not prior to calling this line:
string[] p = Directory.GetFiles(textBoxDir.Text, listBox1.SelectedItem.ToString(), SearchOption.AllDirectories);
I had a similar problem. This is the shortest way i fixed it.
private void button1_Click(object sender, EventArgs e)
{
radioButton1.Checked = !radioButton1.Checked;
string indicadorPais = "Something";
if (listaPaises.SelectedItem != null)
{
indicadorPais = listaPaises.SelectedItem.ToString();
label1.Text = indicadorPais;
}
As a sidenote. My condition originally was comparing listaPaises.SelectedItem.ToString() != null. This broke because i was casting null to a string. The code im sending works fine.
However none of these allow you to go back in and re-select from the list box. Still working on that issue - will update.
while (user == null) {
try {
user = this.lstAdministratorName.SelectedItem.ToString();
} catch {
lstAdministratorName.ClearSelected();
return;
}
}

Categories

Resources