how to display checkbox selected items in ascending order - c#

This is my code:
protected void check1_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < check1.Items.Count; i++)
{
if (check1.Items[i].Selected)
{
comment.Text = "\u2022 "+check1.Items[i].Text +"<br/>"+ comment.Text;
}
}
}
For example if i have checkbox list:
*apple
*Mango
*Orange
*Grapes
and i have selected apple, orange and grapes it is displaying as
grapes
orange
apple
I want it to be displayed as:
apple
orange
grapes

You can sort it using Linq and make use of it
Example :
var sortedCheckBoxes = check1.Items.Where(c => c.Selected).OrderBy(c => c.Text);

First store these items in a List then sort it and then set it to Coment.Text property
protected void check1_SelectedIndexChanged(object sender, EventArgs e)
{
List<string> lst = new List<string>();
for (int i = 0; i < check1.Items.Count; i++)
{
if (check1.Items[i].Selected)
{
lst.Add(check1.Items[i]);
}
}
lst.Sort();
foreach(list l in lst)
{
comment.Text += l;
}
}

Related

C# Check if items in checklistbox are un-checked?

I'm trying to list all items in a directory which has been successful. I need to check if the item's status is "Unchecked", and if it is to give me the name of it in a variable.
TL;DR: If item is unchecked, write item in variable.
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (checkedListBox1.GetItemChecked(e.Index) == true)
{
if (checkedListBox1.CheckedItems.Count != 0)
{
// If so, loop through all checked items and print results.
string s = "";
for (int x = 0; x < checkedListBox1.CheckedItems.Count; x++)
{
if (checkedListBox1.CheckedItems[x] == 0)
{
s = checkedListBox1.CheckedItems[x].ToString();
}
}
MessageBox.Show(s);
}
}
}
This is my current code.
To get a list of all unchecked items:
private void button1_Click_1(object sender, EventArgs e)
{
List<String> items = new List<String>();
for (int i=0; i<checkedListBox1.Items.Count; i++)
{
if (!checkedListBox1.GetItemChecked(i))
{
items.Add(checkedListBox1.Items[i].ToString());
}
}
// ... do something with "items" ...
foreach(String item in items)
{
Console.WriteLine(item);
}
}

How to remove an item selected from a listbox from a list containing multiple objects?

I want a user to be able to select an item from the listbox then press the delete button so that item is deleted from the listbox as well as the allFlights list. How could I change my code so it also deletes the item from the allFlights list?
public partial class Form1 : Form
{
public List<Flight> allFlights;
public Form1()
{
InitializeComponent();
allFlights = new List<Flight>();
Flight flight1 = new Flight("BA431", "Newcastle", "13:00");
Flight flight2 = new Flight("KL126", "Manchester", "16:00");
Flight flight3 = new Flight("CD230", "London", "14:00");
allFlights.Add(flight1);
allFlights.Add(flight2);
allFlights.Add(flight3);
allFlights.Sort();
DisplayArrivals();
}
public void DisplayArrivals()
{
foreach (Flight f in allFlights)
{
lstArrivals.Items.Add(f.ToString());
}
}
private void btnDeleteF_Click(object sender, EventArgs e)
{
for (int i = lstArrivals.SelectedIndices.Count - 1; i >= 0; i--)
{
lstArrivals.Items.RemoveAt(lstArrivals.SelectedIndices[i]);
}
}
}
This should do the trick:
for (int i = lstArrivals.SelectedIndices.Count - 1; i >= 0; i--)
{
allFlights.Remove(lstArrivals.Items[lstArrivals.SelectedIndices[i]]);
lstArrivals.Items.RemoveAt(lstArrivals.SelectedIndices[i]);
}
In your DisplayArrivals() method, instead of adding f.ToString() to your ListBox, add the Flight instance itself, as in lstArrivals.Items.Add(f):
public void DisplayArrivals()
{
foreach (Flight f in allFlights)
{
lstArrivals.Items.Add(f); // <-- add the Flight instance itself
}
}
Make sure to override ToString() for your Flight class to control how it displays in the ListBox.
Then you can cast the selected item back to a Flight instance and use that reference to remove it from your list:
private void btnDeleteF_Click(object sender, EventArgs e)
{
for (int i = lstArrivals.SelectedIndices.Count - 1; i >= 0; i--)
{
Flight f = lstArrivals.Items[lstArrivals.SelectedIndices[i]] as Flight;
lstArrivals.Items.RemoveAt(lstArrivals.SelectedIndices[i]);
allFlights.Remove(f);
// ... possibly do something else with "f" ...
}
}

ListBox get selected index?

I try to get index of selected item in ListBox:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int index = listBox1.SelectedIndex;
}
When I select the second item it returns me index zero again.
Filling ListBox:
private void fillWorkListBox()
{
this.list = manager.works();
this.listBox1.DisplayMember = "name";
this.listBox1.ValueMember = "id";
for (var i = 0; i < this.list.works.Count; i++)
{
string name = "№" + this.list.works[i].id + " - " + this.list.works[i].name;
WorkModel work = new WorkModel();
work.name = name;
work.id = this.list.works[i].id;
listBox1.Items.Add(work);
}
}
It seems that your listbox has the SelectionMode property set to something different from the default. For example if the SelectionMode is MultipleSimple then you cannot use the SelectedIndex property because it is not a list of the elements selected. Instead you use the SelectedIndices collection
void listBox1_SelectedIndexChanged(object sender, EventArgs args)
{
foreach(int x in listBox1.SelectedIndices)
Console.WriteLine(x);
}

move items within a listbox that filled from list of keyvaluepair

I have a list of integers.5 items max.These 5 integers shows 5 indexes of listbox items.I want to move this items in the first 5 places of this listbox.This listbox is filled from a list with this code
uList.Add(new KeyValuePair<int, string>(item.Id, item.Name));
listBoxHome.DataSource = uList;
listBoxHome.DisplayMember = "Value";
listBoxHome.ValueMember = "Key";
indexes is the list of integers refer to index of items.
game.listBoxHome.BeginUpdate();
for (int i = 0; i < 5; i++)
{
foreach (int PlayingInd in indexes)
{
HomeList.Insert(i, HomeList[PlayingInd]);
HomeList.RemoveAt(PlayingInd);
}
}
game.listBoxHome.DataSource = HomeList;
game.listBoxHome.DisplayMember = "Value";
game.listBoxHome.ValueMember = "Key";
game.listBoxHome.EndUpdate();
I use this code to one form:
public void button7_Click(object sender, EventArgs e)
{
Sub sub = new Sub();
foreach (ListItem item in listBox2.Items)
{
uList.Add(new KeyValuePair<int, string>(item.Id, item.Name));
}
sub.HomeList = uList;
}
And in the other form:
private BindingList<KeyValuePair<int, string>> Homelist;
public BindingList<KeyValuePair<int, string>> GetHomelist
{
get { return Homelist; }
set { Homelist = value; }
}
private void button2_Click(object sender, EventArgs e)
{
BindingList<int> indexes = new BindingList<int>();
foreach (int indexChecked in checkedListBox1.CheckedIndices)
{
indexes.Add(indexChecked);
}
Game game = new Game();
foreach (int PlayingInd in indexes)
{
Homelist.Insert(0, Homelist[PlayingInd]);
Homelist.RemoveAt(PlayingInd + 1);
}
game.GetHomelist = Homelist;
this.Close();
}
solved

Sorting a ListBox of objects by attributes

I have a list created by:
List<Song> SongList = new List<Song>();
Populated by a bunch of:
SongList.Add(new Song(songID, "Dirt", "Alice in Chains", "Rooster", "Rock", "02:32"));
The details of songs are populated into a ListBox by:
private void songTitle_TextChanged(object sender, EventArgs e)
{
i = 0;
for (; i < songTitle.Text.Length; i++)
{
songResultBox.Items.Clear();
var songResult = from song in SongList
where song.SongTitle != null && song.SongTitle.Length >= songTitle.Text.Length
&& songTitle.Text == song.SongTitle.Substring(0, i+1)
select new { sId = song.SongID, album = song.SongAlbum, artist = song.SongArtist, title = song.SongTitle,
genre = song.SongGenre, length = song.SongLength };
foreach (var item in songResult)
{
songResultBox.Items.Add(new Song(item.sId, item.album, item.artist, item.title, item.genre, item.length));
songResultBox.DisplayMember = "FullName";
songResultBox.ValueMember = "songID";
}
}
}
Question is: How would I create a button (or 4 in fact) that took the contents of the ListBox 'songResultBox' and sorted its contents by title, album, artist, genre etc.
Create the button, label it depending on what property you want to sort on, add a click event to the button, sort the items (hopefully you've maintained a list of them), then repopulate the listbox:
private bool descendingSongTitleSort = false;
private bool descendingArtistSort = false;
// Artist button clicked event
private void artistButtonClicked(object sender, EventArgs args)
{
Func<Song, IComparable> sortProp = (song => song.Artist);
sortListBox(songResultBox, descendingArtistSort, sortProp);
descendingSongTitleSort = false;
descendingArtistSort = !descendingArtistSort;
}
// Title button clicked event
private void titleButtonClicked(object sender, EventArgs args)
{
Func<Song, IComparable> sortProp = (song => song.Title);
sortListBox(songResultBox, descendingSongTitleSort, sortProp);
descendingSongTitleSort = !descendingSongTitleSort;
descendingArtistSort = false;
}
// Sorting function
private void sortListBox(
ListBox box,
bool descending,
Func<Song, IComparable> sortProperty)
{
List<Song> items = new List<Song>();
foreach (Object o in box.Items)
{
Song s = o as Song;
items.Add(s);
}
box.Items.Clear();
if(descending)
{
items = items.OrderByDescending(sortProperty).ToList();
}
else
{
items = items.OrderBy(sortProperty).ToList();
}
foreach(Song s in items)
{
box.Items.Add(s);
}
}
The descending bools aren't necessary if you don't want to worry about resorting in the opposite direction.

Categories