So I have an idea on how solved my question but i need shorter codes
I have listview with imagelist on it.
everytime listview item selected index change label1.text will also change or updates
here's my code
if (listView1.Items[0].Selected == true)
{
label1.Text = "Number1";
}
if (listView1.Items[1].Selected == true)
{
label1.Text = "Number2";
}
I try to ask if there's a way that utilize the looping to make the code short.
If you are using the ListView
's ItemSelectionChanged
event then you can simply have:
private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
label1.Text = e.Item.Text;
}
But you will require more complicated code if the ListView
's MultiSelect
property is set to true
.
eg
private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
label1.Text = listView1.SelectedItems[0];
}
}
You can use the ListViewItem
's Index
property if you need its position.
To show the selected item, you can try this
foreach (ListViewItem selectedItem in listView1.SelectedItems)
{
label1.Text = selectedItem.Text;
break; // remove it if you have multiple selection but you need thread as well with Thread.Sleep.
}
//OR
label1.Text = listView1.SelectedItems[0].Text;
For custom text
var count = 1;
foreach (ListViewItem selectedItem in listView1.SelectedItems)
{
label1.Text = "Number" + count++;
break; // remove it if you have multiple selection but you need thread as well with Thread.Sleep.
}
You have two main options, for
and foreach
. Foreach
is possibly more readable, but you don't get an index to work with, while for
is less readable but has an index.
int i = 1;
foreach (var item in listView1.Items) {
if (item.Selected == true) {
label1.Text = "Number" + i;
}
i++;
}
//OR DO THIS
for (int i = 1; i <= listView1.Items.Length; i++) {
if (item.Selected == true) {
label1.Text = "Number" + i;
}
}
You can also create a hidden column on the listview and that would be your label text then you could do the following
You would put that in a foreach loop such as;
foreach(ListViewItem item in ListView1)
{
label1.Text = item.HiddenField;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.