Arlind Hajdari Arlind Hajdari - 14 days ago 7
C# Question

Accessing a specific item of a tuple from a listbox of tuples

i've got a problem accessing the items of a tuple that is inserted to a listbox, so i can insert them into a database seperately.

enter image description here

To make it easier for you see the code below.

private void btnInsertToResult(object sender, EventArgs e)
{
Button butoni = sender as Button;

if (butoni.Name == "btnMonday")
{
listRezultati.Items.Add(new Tuple<string, string, string>(Monday.Name, cmbMondayFrom.Text, cmbMondayTo.Text));
}

if (butoni.Name == "btnTuesday")
{
listRezultati.Items.Add(new Tuple<string, string, string>(Tuesday.Name, cmbTuesdayFrom.Text, cmbTuesdayTo.Text));
}

if (butoni.Name == "btnWednesday")
{
listRezultati.Items.Add(new Tuple<string, string, string>(Wednesday.Name, cmbWednesdayFrom.Text, cmbWednesdayTo.Text));
}
if (butoni.Name == "btnThursday")
{
listRezultati.Items.Add(new Tuple<string, string, string>(Thursday.Name, cmbThursdayFrom.Text, cmbThursdayTo.Text));
}
if (butoni.Name == "btnFriday")
{
listRezultati.Items.Add(new Tuple<string, string, string>(Friday.Name, cmbFridayFrom.Text, cmbFridayTo.Text));
}
if (butoni.Name == "btnSaturday")
{
listRezultati.Items.Add(new Tuple<string, string, string>(Saturday.Name, cmbSaturdayFrom.Text, cmbSaturdayTo.Text));
}
}


Thanks in advance.

Answer

You can get items using:

var list = listBox.Items.Cast<Tuple<string, string, string>>().ToList();

Also you can insert them in a BindingList<Tuple<string, string, string>> and bind the ListBox to that list by assigning the binding list to DataSource of ListBox. This way, you can simply add or remove items to the binding list, and the changes will be shown immediately in ListBox.

Note: If you want to save them in database, consider using a DataTable or an entity framework model class, then you can simply save them to database.