How to make each listbox item have its own value via other controls such as numericUpDown and checkbox?

251 Views Asked by At

I am trying to create a program where a listbox has a number of items. Each new item has to be automatically intertwined with a checkbox and a numericUpDown. So for example Item A would have the checkbox ticked, with 50 in the numericUpDown while Item B will have the checkbox unchecked and with 25 in the numericUpDown If possible, I would like to do this via dictionary<> This is the code I have so far:

The class I have created

class MediaClass
{
    public bool Checked { get; set; }
    public int Number { get; set; }
}

This is my dictionary code

public void Dictionary()
{
    var dictionary = new Dictionary<String, MediaClass>();
    listBox_Movielist.DataSource = new BindingSource(dictionary, null);
}

I would also like this to be saved to a text file. My save code is

private void button_Save_Click(object sender, EventArgs e)
{
    SaveFileDialog savefile = new SaveFileDialog();
    savefile.Filter = "Text files|*.txt";
    savefile.Title = "Save As";
    savefile.ShowDialog();
}

My load code is

OpenFileDialog loadfile = new OpenFileDialog();
loadfile.DefaultExt = "txt";
loadfile.Filter = "Text files|*.txt";
loadfile.FilterIndex = 1;
loadfile.CheckFileExists = true;
loadfile.CheckPathExists = true;
loadfile.Multiselect = false;
loadfile.ShowDialog();
System.IO.StreamReader lText = new
System.IO.StreamReader(loadfile.FileName);
listBox_Movielist.Text = lText.ReadToEnd();
1

There are 1 best solutions below

13
On

Asuming your ListBox is called listbox, add this in the constructor for your window:

listbox.SelectionChanged += (sender, e) =>
{
    var item = listbox.SelectedItem as ListBoxItem;
    string media = item.Content as string;
    if (media != null)
    {
        //set checkbox to dictionary[media].Checked
        //set updown to dictionary[media].Number
    }
};

I'm not quite sure why you declare your dictionary in an extra method. This will make it impossible to reference outside of that method. What you probably want is to have the dictionary be a private field. Something like

private Dictionary<String, MediaClass> dictionary = new Dictionary<String, MediaClass>();

somewhere in your window class.