0


I'm making a program that catalogs the names of the people I add in a listbox and save all the content to a file when you close the program.
Each line of the file is for a person:

Tommy
Marco
James
Dylan

When the program starts, the file data is loaded and add the names to listbox.
All this works great, but now I'm having trouble making something else.
Each person on the list need a variable to indicate whether it has paid and I want to save this variable together with his name on the file.
For this, I have:

bool paid;
private void checkbox_Paid_CheckedChanged(object sender, EventArgs e)
{
    paid = true;
}

I have only one checkbox, and it needs to differ from each person in the listbox, according to the selected in the event:

private void listDOF_SelectedIndexChanged(object sender, EventArgs e)
{

}

But I do not know how to write this bool in the file for each person, save to the file together with name and load it.
I've tried something like:

foreach(string purchasers in listDOF.Items)
{
    arq.WriteLine(purchases, paid);
}

Obviously this do not worked, I do not know how to assign the bool for each one of the purchasers and write it in the file.
I'm using .NET 4.5 in a WFA.
Thanks all in advance, if I able to do this, I will give a big step toward the knowledge.

Hypister
  • 147
  • 4
  • 17
  • There are dozends of options on how to achieve this. In the end you need to build-up a string that reflects the line you want to write to the file. Try `arq.WriteLine("{0} {1}", purchases, paid);` [for example](http://msdn.microsoft.com/en-us/library/60scc1f1(v=vs.110).aspx). – Christian.K Aug 27 '14 at 15:10
  • 1
    Populate the listbox with a Person class, and then save the people to an xml file would be my advice (look up serialization) – Sayse Aug 27 '14 at 15:14
  • First you need to decide which fie format you want to use. I guess in your case I would go with csv. Then write line by line like: Tommy,true and so on. When you read the line just split it up by your Separator (,) and analyze if it the second string says true or false. – nothing9 Aug 27 '14 at 15:14
  • @Christian.K this seems to be the right way, it write the name and the variable in the file, but when load to the listbox, load like "Tommy False" and if I check the checkbox, then in the next time load "Tommy False True". I need to assign for each person and don't be identified as a string by the program. – Hypister Aug 27 '14 at 15:15

2 Answers2

3

First of all I would store the persons in a list in the application otherwise you will only have one bool for all the persons in the application and everyone will be set as payed or not payed.

public class Person
{
   public string Name { get; set; }
   public bool Payed { get; set; }
}

public List<Person> Persons { get; set; }

As simple way is to save it in a SCV file. Semicolons between fields and new row per post

Tommy; true
Marco; true

Then save like this

foreach(var person in Persons)
{ 
   arq.WrtieLine("{0};{1}", person.Name, person.Payed);
}
AxdorphCoder
  • 1,104
  • 2
  • 15
  • 26
  • But how to use this in the checkbox_check event? – Hypister Aug 27 '14 at 16:01
  • In your case I would get the selected name from the listbox and then select the person in the Persons list with the same name and then set Payed to the value of the checkbox. Another approach would be to databind Persons to the listbox and get the selected person by SelectedItem property on the listbox. I would also use an uniqe idntifier on the Person class. – AxdorphCoder Aug 27 '14 at 16:32
1

I believe that this is a good case to turn your text file into JSON.

For example:

[
  { name: "Tom", hasPaid: true },
  { name: "Matias", hasPaid: false } // Urgh!
]

And In C# you can build up this JSON using anonymous objects:

List<object> people = new List<object>();
people.Add(new { Name = "Tom", HasPaid = true });

Finally, you can serialize to JSON using JSON.NET:

File.WriteAllText(@"C:\myfile.json", JsonConvert.SerializeObject(people));

...or deserialize it:

List<object> people = JsonConvert.DeserializeObject<List<object>>(File.ReadAllText(@"C:\myfile.json"));

Update

Maybe you should use an concrete class rather than an anoymous object, because the later is inmutable and you're going to get in troubles if you need to data-bind the object list to the whole ListBox.

You can declare a simple class like this:

public class Person 
{
    public string Name { get; set; }
    public bool HasPaid { get; set; }
}

...add persons this way:

List<Person> people = new List<Person>();

Person person = new Person();
person.Name = "Tom";
person.HasPaid = true;
people.Add(person);

File.WriteAllText(@"C:\myfile.json", JsonConvert.SerializeObject(people));

And when it comes to deserializing the whole JSON array:

List<Person> people = JsonConvert.DeserializeObject<List<Person>(File.ReadAllText(@"C:\myfile.json"));

Update 2

It seems like you don't know you can bind a list to Windows Forms controls. See for example the following MSDN article.

Instead of List<T> you can use BindingList<T>. Check this CodeProject guide.

This way, when you add an item to the whole BindingList<T> the ListBox control will be automatically populated. If you remove one, it will also dissapear from the UI.

Both Windows Forms and Windows Presentation Foundation are powerful and productive if you leverage data-binding (also in Web development, say KnockoutJS!).

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
  • That's nice, my friend! But my projects actually works loading the file, if it exists, when the program starts and during the use of the application, the user can add or remove pesons in ListBox. All the data is saved when the program is closed. I add new persons cathing the text typed from one textbox: listaDOF.Items.Add(box_AddPerson.Text); On close event, if listbox has names, they are saved in the file and if has not, the file are not created. In case, I have one checkbox to assign the variable for the selected person in the list. How to implement the variable by this way to add names? – Hypister Aug 27 '14 at 22:08
  • The Person List needs to get the names from the listbox and turn the variable according to the checkbox value for the selected person in the list. – Hypister Aug 27 '14 at 22:11
  • @Hypister You need to use data-bind, where you define that "Name" is the display text of the ListBox and you set the `HasPaid` under the hoods. – Matías Fidemraizer Aug 28 '14 at 05:36
  • I've tried this in the click event for the button to add person: `if(box_AddPerson.TextLength != 0) { Person purchaser = new Person(); purchaser.Name = box_AddPerson.Text; purchaser.Paid = false; Purchasers.Add(purchaser); listaJogs.Items.Add(purchaser.Name); box_AddPerson.Text = ""; }` – Hypister Aug 28 '14 at 14:45
  • This add on the list, but when I save the file in the close event of the program with: `File.WriteAllText(file, JsonConvert.SerializeObject(Person));` The file is not written with the name. The file just contais "[]" And in the load event of the program, I tried to use: `List Purchasers = JsonConvert.DeserializeObject (File.ReadAllText(file)); listDOF.Items.AddRange(Purchasers);` This don't work, I have errors. – Hypister Aug 28 '14 at 14:50
  • @Hypister If it stores `[]` is because the list is empty. Check what you're serializing (watch the variable you're serializing during debugging) – Matías Fidemraizer Aug 28 '14 at 15:03
  • How about the error in the line to load and to add the content of the file in listbox? System.Collections.Generic.List is a 'type' but is used like a 'variable'. And to add to the list: The best overloaded method match for 'System.Windows.Forms.ListBox.ObjectCollection.AddRange(System.Windows.Forms.ListBox.ObjectCollection)' has some invalid arguments. – Hypister Aug 28 '14 at 15:07
  • @Hypister I believe you're lost!! Uhm you need to learn more about data binding. The errors you mention in your comments have nothing to do with your original question. It's more about using the right classes. – Matías Fidemraizer Aug 28 '14 at 15:17
  • Now is writing alright. I'm having trouble in how to load the name to the listbox and in turn the variable for the actually person selected in the list when I check the checkbox. Can you give me a code example? – Hypister Aug 28 '14 at 15:28
  • @Hypister Sincerely, it has been a long time since I did my last step in WinForms. BTW, maybe this other Q&A here in StackOverflow might help you! http://stackoverflow.com/questions/7485631/winforms-how-to-bind-the-checkbox-item-of-a-checkedlistbox-with-databinding – Matías Fidemraizer Aug 28 '14 at 15:33
  • I will take a look. I'm trying to load the "Name" part from json file to the list. – Hypister Aug 28 '14 at 15:35
  • @Hypister I understand you're deserializing the whole JSON into a list back. I mean, using `JsonConvert.DeserializeObject` – Matías Fidemraizer Aug 28 '14 at 15:37
  • @Hypister It seems like it has turned into a great and interesting learning adventure, isn't it? I suggest that if you put more effort, if you master data-binding, you'll never look back even in other programming languages. – Matías Fidemraizer Aug 28 '14 at 15:39
  • haha' of course it was by this way. Learning is always good, no matter how! This sounds great, I will learn more about data binding. – Hypister Aug 28 '14 at 16:06