I am doing some more coding on listView, and I can not figurate it out how to salve the problem that there is always just one checkBox on the listView checked.

On the listView I have some names. When I load it there is already a checked name - so far so good.

But I would like to do the code, that when I will check another checkBox, this one has to check and the other one which was checked before, it has to uncheck.
Anyone knows how to help me out with this?

So that there will always be just one checkBox checked.

bool isChecking;
bool canCheck;
private void listView1_ItemCheck(object sender, ItemCheckEventArgs e)
{
    if (!isChecking && canCheck)
    {
        isChecking = true;
        foreach (ListViewItem item in listView1.Items)
        {
            item.Checked = false;
        }
        listView1.Items[e.Index].Checked = true;
        e.NewValue = CheckState.Checked;
        canCheck = false;
        isChecking = false;
    }
    else
    {
        if (isChecking)
        {
            e.NewValue = CheckState.Unchecked;
        }
        else
        {
            e.NewValue = e.CurrentValue;
        }
    }
}

private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    // We can't unlock the lock if the value doesnt change.
    if (!listView1.GetItemAt(e.X, e.Y).Checked)
    {
        canCheck = true;
        listView1.GetItemAt(e.X, e.Y).Checked = true;
    }
}

Here is another solution. Whenever a box is unchecked, there is no need to do anything. When the item that is checked is hit, we want to uncheck everything else.

private void lvMeets_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (!e.Item.Checked)
                return;

            foreach (ListViewItem item in lvMeets.Items)
            {
                if (item == e.Item)
                    continue;

                item.Checked = false;
            }
        }
private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            foreach (ListViewItem lstItem in listView1.Items)
            {
                if (lstItem.Text != e.Item.Text)
                {
                    lstItem.Checked = false;
                }
            }
        }

So many code...

listView1.SelectionMode = System.Windows.Controls.SelectionMode.Single;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.