Click a listbox item and display textfile text in labels - c#

I'm getting stuck clicking a listbox item (the items in my listbox is .txt files in a folder) and displaying the values in the .txt file.
the values in the .txt files are all seperated with a "," and I want each Split item to display in labels on my form.
my file path is: System.AppDomain.CurrentDomain.BaseDirectory + "data"
my .txt file names are the names of the selected item in my listbox.
I have a basic idea of what should happen, but I have no clue how to express this in code.
My Code:
private void custList_MouseClick(object sender, MouseEventArgs e)
{
string foldr = System.AppDomain.CurrentDomain.BaseDirectory + "data";
string file = custList.SelectedIndex.ToString();
}
Thanx in advance

Before i go on answering this question, please read How to ask. This will help you better understand this community and ask better questions(to get better support).
Next on, do some research. From a first glance, it looks like you are asking someone to do the homework for you. Anyways, i am not here to be tough on you. I will point you out a few things. Try to understand them and utilize them.
Note that even though it may seem as such but i am not a fan of spoon-feeding so be sincere and do your research.
Let's start with your text file. As you mentioned, it contains values. C#, being a versatile & mature language has a lot of functions,methods,classes pre-built to help boost your programming experience. Such a method is ReadAllText, a part of the File class. In the simplest words, this method opens a text file, reads it, returns it's value. A sample use of this method could be :
string TextFromFile = File.ReadAllText(File_Path_Goes_Here);
Moving on... Your text file has multiple values separated by comma(,). In such cases, each value needs to read as a separate value upon retrieving or displaying. So, you want a List of the values, end of story. In C#, you have a wide range of generic lists to use from. As the values in the text file are simple strings, you can use a List<string> in this regard. A basic usage example of List<string> would be :
List<string> TestList1 = new List<string>();
TestList1.Add("First Value"); TestList1.Add("Second Value");
///or
List<string> TestList1 = new List<string>(){ "First Value", "Second Value" };
In your particular case, File.ReadAllLines is worth an example. The method opens a text file, reads it, closes it. Of course it returns the value read from the text file, as an array. So, when passing values to the generic list, you can simply make use of this method. Example :
...... new List<string>(File.ReadAllLines(Path_Of_File_Goes_Here));
The only twist here is that the values in your text file are in a line(maybe) and also are separated by comma. So, what do you think should work here ? ReadAllText or ReadAllLines ? I will leave it upto you.
Once values are read from the file, we can make use of the Split function to split the values upon each occurrence of a comma(,). A simple example :
List<string> NameList = "Josh,Riley".Split(',').ToList<string>();
And last but not the least, the headline of the question which doesn't seem to have anything to do with the post itself, here's what you can take a look at :
Control Click Event
ListBox.GetItemText
Tip: The SelectedItem property of the ListBox class returns or sets the selected item of a listbox.
I hope this has been helpful. Do pay attention to all that's mentioned above. It may be a bit hard to follow up with at first, but remember, Consistency is the hallmark of the unimaginative.
....Yeah, that's not my quote. Gotcha!

I don't know where you want to show the values of your text file, so I will just provide you what you need to retrieve those informations.
To get values from your file:
public string[] GetValues()
{
string[] values;
using(StreamReader sr = new StreamReader(Path.Combine(foldr, file))
{
string text = sr.ReadToEnd();
values = text.Split(',');
}
return values;
}
Then you can show them using an array:
public void Main()
{
string[] values = GetValues();
foreach(var value in values)
{
Console.WriteLine(value);
}
}
Hope this helps.

Related

How to save multiple strings in distinct locations and not in one string

I recently started learning about programming with C# and I have encountered a little problem with my small task that I got.
But first let me just go through a little bit what I learned so far about strings.
So, string text = Console.ReadLine(); saves whatever the user writes into that variable.
Next, I worked with a Backpack code where the user can 1. Add items in the backpack and 2. Present the items in the backpack. Here I worked with the += operator so that whenever the user added an item it would be added to the string variable.
Now I am working with a diary/blog code. The user can:
Write a new text (with a title).
Search and present the texts written.
I am stuck because I can't just have one string variable for the text that the users writes because it will be overwritten every time the user adds a new text. And I can't use += operator since I don't want to add more text to my string variable. Every time the user adds a new text it has to be saved into a new string variable (I guess?).
I just don't know how to write this code.
A good way to fix your issue is to use Classes. Maybe you can create a Blog Class with two properties Title and Body and then all you have to do is to simply create a list of Blogs.
class Blog
{
string Title {get;set;}
string Body {get;set;}
}
Each object of Blog Class represent a new post and a list of blog will give you the list of all the blog posts.
List<Blog> blogs = new List<Blog>();
You can use a generic collection like List. They are build for gathering items of one certain type. In your case it would be: List<string> allTexts. You can add strings to it with the Add method:
List<string> allTexts = new List<string>();
string newText = Console.ReadLine();
allTexts.Add(newText);
and you can access them via the [ ] operator
string textNr4 = allTexts[3];
Note: indexing starts with 0!
If you like to search for certain parts of a text you could use LINQ
string searchWord = "and";
List<string> allMatchedTextes = allTexts.Where(text=>text.Contains(searchWord)).ToList();
this will return all strings that contain the searchWord

Store tab delimited clipboard data to list of objects in C#

I am new to C# but am working on a project at work. The task is to copy an array of values from one application to the clipboard and then to store those values in a list of objects in C#. I have created private properties for each field represented by the columns in the copied data, but i cannot figure out how to parse the data from the clipboard and store it in each property. Hopefully this makes sense. I'm having trouble even figuring out where to begin despite extensive searching. Any help would be greatly appreciated.
As suggested by Jack A. in the comments, use String.Split().
Something like...
if (Clipboard.ContainsText())
{
string str = Clipboard.GetText();
string[] values = str.Split("\t".ToCharArray());
// ... do something with "values" ...
xxx.aaa = values[0];
xxx.bbb = values[1];
xxx.ccc = values[2];
// etc...
}
else
{
MessageBox.Show("No Text in the Clipboard!");
}
You should probably check to make sure the right number of columns were present after splitting, though:
if (values.Length == 5)
{
// ... do something with "values" ...
}
I used this recently in another project: http://joshclose.github.io/CsvHelper/
Although you aren't using a CSV per se, you are using delimited data and it allows you to specify the delimeter. If you convert your text into a text reader similar to this post: In C#, how can I create a TextReader object from a string (without writing to disk), it will easily transfer the data to an object of your choosing once you have mapped it

Load string collection from external data in C#

I have a class that has a collection of strings that is used to validate values before storing them. The declaration for the collection looks like this:
public readonly System.Collections.Specialized.StringCollection RetentionRange =
new System.Collections.Specialized.StringCollection()
{ "NR", "AR", "PE", "EX", "LI", "TE", "FR" };
I'd like to maintain the list of valid codes outside of the compiled class. How do I go about that? BTW, there's no requirement for the strings to be limited to two characters, they just happen to be in the current scheme.
EDIT: By "external data" I mean something like a config file.
You can store a StringCollection in the AppSettings.
Each value is separated by a new line.
Here's a screenshot (german IDE but it might be helpful anyway)
You can read it in this way:
var myStringCollection = Properties.Settings.Default.MyCollection;
foreach (String value in myStringCollection)
{
// do something
}
Storing it in a text file is an option.
How to store:
var dir = #"somedirectory\textfile.txt";
var text = string.Join(",",RetentionRange.Cast<string>());
File.WriteAllText(dir,text);
How to retrieve:
var text= File.ReadAllText(#"somedirectory\textfile.txt");
foreach(var str in text.Split(","))
RetentionRange.Add(text);
The right answer to your question depends a great deal on why you want to store the strings outside the assembly.
Assuming the reason you want this is because the collection of strings is expected to change over time, I would suggest you create your own System.Configuration.ConfigurationSection implementation that defines one of the elements as a System.Configuration.ConfigurationElementCollection instance. If this is a tad too complicated for your requirements, then an appSettings key with a value consisting of a comma separated list of strings (from which you would build your StringCollection at runtime) might actually be a better solution.
The answers to this question have examples of both approaches.

How to keep a TXT file synced with a List<string>

So, I'm making a text based game in C#, and I am creating a profile feature. It already creates a new TXT file when it is executed for the first time and stores it in the appdata folder. Now, here is what is in that TXT file;
NAME=[$]
REP=[0]
The 'NAME' operator is for a personal alias, and is what I am working on at the moment. What I need it to do, is upon entering a command;
alias Example
It will modify a List which contains exactly that, in short, synced with the TXT file. I have tried many, many different ways, including;
case "alias":
string joined = string.Join(",", profileList.ToArray());
string[] joineone = joined.Split(',');
profileList.Clear();
foreach (string var in joineone)
{
if (var.StartsWith("NAME"))
{
var.Replace(getStringBetween(var, "[", "]"), preCut[1]);
}
profileList.Add(var);
}
Invoke(new _rewriteProfile(rewriteProfile));
break;
and a much shorter version;
profileList[0].Replace(getStringBetween(profileList[0],"=[", "]"), preCut[1]);
Where profileList is the synced one with the TXT file and getStringBetween gets a string between two characters. It is also hooked up to a replace, to replace it with the first "cut", which in this case is 'Example'. The thing is, it never changes. The text just does not change in the list. I have NO IDEA why. I am using .NET 2.0 by the way.
Any help would be highly appreciated!
var = var.Replace(getStringBetween(var, "[", "]"), preCut[1]);
Check if the txt file is read only...... or maybe your method (getStringBetween) does not return any thing.

String manipulation in C#: split on `/`

I need to extract headstone data from an inscription file (structured text file). From this file I am supposed to extract the name of a deceased person, date of birth (or age) and also personal messages. The application should be able to analyse a raw text file and then extract information and display it in tabular form.
The raw text files looks like this:
In loving memory of/JOHN SMITH/who died on 13.02.07/at age 40/we will
miss you/In loving memory of/JANE AUSTIN/who died on 10.06.98/born on
19.12.80/hope you are well in heaven.
Basically / is a delimiter and the name of a deceased person is always in capital letters. I have tried to use String.Split() and substring methods but I can't get it to work for me; I can only get raw data without the delimiter (Environment.Newline) but I don't know how to extract specific information.
You'll need something like:
Open your data file (System.IO)
For each line, do (tip: pick a stream where you can read line by line)
Split them by "/" getting a string[]
Arrays in C# starts at 0; so splitted[1] will be that name, ans so on
Store that information in a managed collection (maybe to use generics?)
Display that collection in a tabular view
Check out How to: Use Regular Expressions to Extract Data Fields. I know the example is in C++, but the Regex and Match classes should help you get started
Here is another good example of parsing out individual sentences.
I would have thought something like this would do the trick
private static void GetHeadStoneData()
{
using(StreamReader read = new StreamReader("YourFile.txt"))
{
const char Delimter = '/';
string data;
while((data = read.ReadLine()) != null)
{
string[] headStoneInformation = data.Split(Delimter);
//Do your stuff here, e.g. Console.WriteLine("{0}", headStoneInformation[0]);
}
}
}

Categories