C# Listbox sort items - c#

Im new to programming and Im having a problem with a listbox. Im reading text from a file, and I want the last file in the file to be the first in the listbox. How to I do this??
This is a school project :)
This is the code I have so far:
if (File.Exists(file))
{
FileInfo fileInfo = new FileInfo("nema.csv");
StreamReader read = fileInfo.OpenText();
while (!read.EndOfStream)
{
listBox1.Items.Add(read.ReadLine());
}
read.Close();
}

it's hard to tell without code but basically you have to use Insert(0,item) instead of Add(item) to reverse the order. The code coud look something like this:
using(var reader = System.IO.File.OpenText(pathOfFile))
{
myListBox.Items.Insert(0, reader.ReadLine());
}

Read the contents of the file.
Put them in a list
Add the items that
are in the list to the ListBox, but make sure you start from the last
item in the list, and go to the first.

To add a new object at the first place of the listbox
listbox.Items.Insert(0, objectToAdd)

I assume you to handle read textfile
While Reading TextFile store all string in a List Collection.
List<string> listItems = new List<string>();
FileStream fs = new FileStream(#"c:\YourFile.txt", FileMode.Open);
StreamReader sr = new StreamReader(fs);
string line = "";
int lineNo = 0;
do {
line = sr.ReadLine();
if (line != null) {
listItems.Add(line);
}
} while (line != null);
listItems.Sort();
foreach(string s in listItems)
{
yourListBox.Items.Add(s);
}

Just use Listview either than listbox.
Go to properties of ListView
Click the SORTING
Choose descending

Related

In C# can we update a text file line with new record while reading the same file

I have .text File (with 400K rows). I need to read that file and If i find (AB,CB,DE,FG) in certain position (35, 2) in each row, I need to replace that with new value which I already have in dictionary object.
this is my dictionary with list of policy number and respective group:
ListofPolicy[10001,MM]
ListofPolicy[10005,KK]
ListofPolicy[10011,NN]
ListofPolicy[10018,YY]
ListofPolicy[10020,GG]
etc...
This is my sample .txt file: I need to read the line.Substring(35, 2) will tell us which group it is.
P00002398911100010131220111061553XXAB549099QSTJDK6016
HUI001004117577408867289000000007209171
P00002398918100058882220111061459YYLT518435BIVQZC1855
P00002398916726561656220111103331XXKY518435BIVQZC1855
PPP001CSTON
P00002398911001136778220111103329XXCB511100QSBUPO1128
HUI001004117577408867289000000007209171
P00002398911001888877220111103323XXKI518435BIVQZC1855
PMT001CSTON
P00002398911002066656220111103320YYFG511100QSBUPO1128
HUI001004117183000000007209169
P00002398917409185763220111103316XXDF511100QSBUPO1128
How do I approach this ?
If I understand you correctly, you need something like that:
string content = "";
using (StreamReader sr = new StreamReader("path\\to\\your\\file.txt"))
{
content = sr.ReadToEnd();
}
using (StreamWriter sw = new StreamWriter("path\\to\\your\\file.txt"))
{
foreach (string line in content.Split('\n'))
{
if (yourDictionary.Keys.Contains(line.Substring(35, 2)))
{
sw.WriteLine($"{line.Substring(0, 35)}{yourDictionary[line.Substring(35, 2)]}{line.Substring(37, line.Length - 37)}");
}
else
{
sw.WriteLine(line);
}
}
}

C# WPF How do I display the contents of a .txt file into a list box?

Say I have a txt file with this content:
Tom, 11
Jason, 12
Gary, 13
Ted, 14
The WPF is just a list box.
What would I need to do for the list box, to show the names inside the txt file when I start the program.
This is a very simple question, but I cant figure it out. I don't know where the txt file needs to be saved and I don't know how to call it in the ".cs"
This is code which read next line to list,then read how to add this to listbox
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
{
lines.Add(line);
}
}
This is example how to binding list to listbox:
eventList.ItemsSource = lines;
Text file can be anywhere as you can specify path to it while opening. You can put it inside solution folder to make path shorter.
Then in main method you write something like
var MyList = new List<string>();
using (var streamReader = File.OpenText(pathToYourTextFile))
{
var s = string.Empty;
while ((s = streamReader.ReadLine()) != null)
MyList.Add(s);
}
myListbox.ItemsSource = MyList;

Adding to listbox from multiple files and deleting doubled items

As you can read in the title, I am trying to add listbox items to a listbox from multiple files. But I don't know how to read from all these files and how to delete the doubled lines (as some txt-files contain the same information).
A new file gets added every day, so I can't just read them all manually.
My code so far:
string directory = System.AppDomain.CurrentDomain.BaseDirectory;
DirectoryInfo dinfo = new DirectoryInfo(directory);
FileInfo[] Files = dinfo.GetFiles("*.txt");
First of all you need to identify every file you need to read.
Once you have all the files you need to read the data from each file into some form of storage for example a DataTable.
Once you have filled the DataTable you will need to populate the ListBox with the data.
From what you've got so far it looks like your next step will be to collect the data from each of the files (we can deal with removing duplicates afterwards).
So perhaps:
HashSet<something> myCollection = new HashSet<something>();
// perhaps <something> is just a string?
foreach (var file in Files)
{
// Collect what you need and pop it in the collection
}
// Remove duplicates
To get the info out of the files you'll probably need a StreamReader.
Fore removal of duplicates try HashSets.
you can try this code:
in this code all unique data will be stored in lstData and you can bind your control using this
string directory = System.AppDomain.CurrentDomain.BaseDirectory;
DirectoryInfo dinfo = new DirectoryInfo(directory);
FileInfo[] Files = dinfo.GetFiles("*.txt");
List<string> lstData = new List<string>();
foreach (var file in Files)
{
using (StreamReader sr = File.OpenText(file.FullName))
{
string s = String.Empty;
while ((s = sr.ReadLine()) != null)
{
if (!lstData.Contains(s))
{
lstData.Add(s);
}
}
}
}

How to close file that has been read

So im trying to close a file (transactions.txt) that has been open that i've used to read into a textbox and now I want to save back to the file but the problem debug says that the file is in use so I need to find a way to close it. Can anyone help me with this? Thanks!
SearchID = textBox1.Text;
string ID = SearchID.ToString();
bool idFound = false;
int count = 0;
foreach (var line in File.ReadLines("transactions.txt"))
{
//listView1.Items.Add(line);
if (line.Contains(ID))
{
idFound = true;
}
//Displays Transactions if the variable SearchID is found.
if (idFound && count < 8)
{
textBox2.Text += line + "\r\n";
count++;
}
}
}
private void SaveEditedTransaction()
{
SearchID = textBox1.Text;
string ID = SearchID.ToString();
bool idFound = false;
int count = 0;
foreach (var lines in File.ReadLines("transactions.txt"))
{
//listView1.Items.Add(line);
if (lines.Contains(ID))
{
idFound = true;
}
if (idFound)
{
string edited = File.ReadAllText("transactions.txt");
edited = edited.Replace(lines, textBox2.Text);
File.WriteAllText("Transactions.txt", edited);
}
The problem here is that File.ReadLines keeps the file open while you read it, since you've put the call to write new text to it inside the loop, the file is still open.
Instead I would simply break out of the loop when you find the id, and then put the if-statement that writes to the file outside the loop.
This, however, means that you will also need to maintain which line to replace in.
So actually, instead I would switch to using File.ReadAllLines. This reads the entire file into memory, and closes it, before the loop starts.
Now, pragmatic minds might argue that if you have a lot of text in that text file, File.ReadLines (that you're currently using) will use a lot less memory than File.ReadAllLines (that I am suggesting you should use), but if that's the case then you should switch to a database, which would be much more suited to your purpose anyway. It is, however, a bit of an overkill for a toy project with 5 lines in that file.
Use StreamReader directly with the using statement, for example:
var lines = new List<string>();
using (StreamReader reader = new StreamReader(#"C:\test.txt")) {
var line = reader.ReadLine();
while (line != null) {
lines.Add(line);
line = reader.ReadLine();
}
}
By using the using statement the StreamReader instance will automatically be disposed of after it's done with it.
You can try with this:
File.WriteAllLines(
"transactions.txt",
File.ReadAllLines("transactions.txt")
.Select(x => x.Contains(ID) ? textBox2.Text : x));
It works fine, but if the file is big you have to find other solutions.
You can use the StreamReader class instead of the methods of the File class. In this way you can use, Stream.Close() and Stream.Dispose().

C# listbox split to another 2 listboxes

Problem:
I have 1 ListBox which loads a text file contain:
ip:port
ip:port
ip:port
What I want to do is, once I've loaded the text file into the list box, I want to have the 'ip' to go into a different listbox and the 'port' into a different listbox. This is first time working on a project like this.
// if you wanted to do it with LINQ.
// of course you're loading all lines
// into memory at once here of which
// you'd have to do regardless
var text = File.ReadAllLines("TestFile.txt");
var ipsAndPorts = text.Select(l => l.Split(':')).ToList();
ipsAndPorts.ForEach(ipAndPort =>
{
lstBoxIp.Items.Add(ipAndPort[0]);
lstBoxPort.Items.Add(ipAndPort[1]);
});
Something like
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
string[] ipandport = line.split(":");
lstBoxIp.Items.Add( ipandport[0] );
lstBoxPort.Items.Add( ipandport[1] );
}
}

Categories