Reputation: 330
I have done this before and I have a way of doing it, but I want to make sure it is the best way. I have a ListView in Details view. I also have a button. I only want that button to be enabled if there is an item selected (multiselect is disabled). Items will be added and removed to this listview but the button should be enabled anytime there is a selected item and disabled otherwise.
My event handler:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
button1.Enabled = true;
else
button1.Enabled = false;
}
That is what I have, just wondering if that will always work or are there freak incidents where it fails? Like if I delete or add things or anything else?
Upvotes: 2
Views: 5486
Reputation: 3834
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 9; i++)
{
listView1.Items.Add("kashif");
}
button1.Enabled = false;
}
private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
button1.Enabled = listView1.SelectedItems.Count > 0;
}
private void button2_Click(object sender, EventArgs e)
{
foreach (ListViewItem v in listView1.SelectedItems)
{
v.Remove();
}
}
}
Before Button2 Click
After Button2 click
Upvotes: 2
Reputation: 5194
It'd be better if you show what you have - but in short, you start with the button disabled, and in the list view selectedindexChanged event enable the button if the list view has a selectedItems.Count of 1. Disable it if no item is selected. Here's a link which may help: ListView selectedindexchanged
Upvotes: 3