C#. Checkboxes become unchecked - c#

I have a problem, that I can't solve.
I am writing an application that will help to change system proxy easily. It has a listView with some items. These items have checkboxes.
Logic of application demands that only one item can be checked at a time, so I have following code to make sure it works well:
private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
listView1.ItemChecked -= listView1_ItemChecked;
foreach(ListViewItem item in listView1.Items)
{
if(item != e.Item)
{
item.Checked = false;
}
}
listView1.ItemChecked += listView1_ItemChecked;
}
Also my application needs to check some value in registry on it's start and compare it's text with my items in listView.
I am doing it like that:
private void GetProxyFromRegistry()
{
RegistryKey SystemProxy = Registry.CurrentUser.CreateSubKey(#"Software\Microsoft\Windows\CurrentVersion\Internet Settings");
try
{
string UsedProxy = SystemProxy.GetValue("ProxyServer").ToString();
foreach (ListViewItem item in listView1.Items)
{
if (UsedProxy == item.Text + ":" + item.SubItems[1].Text)
{
item.Checked = true;
}
else
{
item.Checked = false;
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
The problem is that none of the listView1.Items will be checked except last one when used.
I know that it's because of listView1_ItemChecked(), but I do not know how to solve it the other way.
Can you help me find a solution how to either uncheck all other checkboxes, or find a workaround to make correct item be checked?

this may be a bit of a simple solution to only have one checkbox used at a time, but it works for me. create a listview.click event and then do the following:
private void listView_Click(object sender, System.EventArgs e)
{
foreach (ListViewItem item in listView.Items)
{
item.Checked = false;
}
}
Bit of a hack really, but works great.

So starting with your ItemCheck event, it should be like this:
void listView1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.currentValue == CheckState.Checked)
return;
foreach (ListViewItem item in listView1.Items)
{
if (item.Index != e.Index)
{
item.Checked = false;
}
}
}
For the next issue, I'd suggest setting a breakpoint at this line of code here:
if (UsedProxy == item.Text + ":" + item.SubItems[1].Text)
When the breakpoint is hit (on the last index), check to see what's different about that item in comparison to the others (look at case sensitivity, for instance).

Related

how to check whether items present in list box & how to check list box has duplicates? in csharp

private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox1.Text);
}
private void button2_Click(object sender, EventArgs e)
{
string val = listBox1.Text.Trim();
if (listBox1.Items.Contains(val)) {
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
else
{
MessageBox.Show("There is no items present");
}
}
elements are entered from text box to list box, If entered the same data,. how to check? or msg box should display and
while deleting items from the list box if there is no items how to i get to know.
You can check if the value entered in the textbox is already in the listbox or not:
bool listContainsItem = Listbox.Items.Any(item => item.Value == textboxValue);
if(listContainsItem)
{
// ... item is in listbox, do your magic
}
else
{
// ... item is not in listbox, do some other magic
}
You can do this in the Onchange event of your textbox, or when clicking a button, ... give us more context so we can provide you a better solution.
You can use a HashSet as data source to make sure your list contains unique elements.
In example :
HashSet<string> ListBoxSource = new HashSet<string>();
private void button2_Click(object sender, EventArgs e)
{
string val = listBox1.Text.Trim();
// ListBoxSource.Add(val) Return true if val isn't present and perform the adding
if (ListBoxSource.Add(val))
{
// DataSource needs to be a IList or IListSource, hence the conversion to List
listBox1.DataSource = ListBoxSource.ToList();
}
else
{
MessageBox.Show("Item is already in list");
}
}
You may check for duplicated item by looping through each item in the list to be compared with name of item to be added when add button is clicked:
private void addBtn_Click(object sender, EventArgs e)
{
bool similarItem = false;
if (!String.IsNullOrEmpty(itemText.Text.Trim()))
{
foreach (string listItem in itemListBox.Items)
{
if (listItem == itemText.Text)
{
MessageBox.Show("Similar item detected");
similarItem = true;
break;
}
}
if(!similarItem)
itemListBox.Items.Add(itemText.Text);
}
}
To prompt user when delete button is clicked when there is no item, the selected index will be -1, u may use that as the condition to prompt user:
private void deleteBtn_Click(object sender, EventArgs e)
{
if (itemListBox.SelectedIndex > -1)
itemListBox.Items.RemoveAt(itemListBox.SelectedIndex);
else
MessageBox.Show("No item exist in the list box, operation fail");
}

How to enable a button if an item in a listbox is selected

I tried this but it doesn't work. They're still greyed out even when I select stuff.
btnVoirFiche.Enabled = false;
btnEchangerJoueur.Enabled = false;
if (lstJoueurs.SelectedIndex != -1)
{
btnVoirFiche.Enabled = true;
btnEchangerJoueur.Enabled = true;
}
else
{
}
You'll want to handle the ListBox.SelectedIndexChanged event, and within your handler you're going to check if the specific value is the selected one, and then set you button's enable property accordingly.
Something like this:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(listBox1.SelectedIndex != -1)
{
btnVoirFiche.Enabled = true;
btnEchangerJoueur.Enabled = true;
}
else
{
//whatever you need to test for
}
}
Cheers
EDIT: I'm not too sure what your logic for button's enabled property is, so my answer is pretty generic. If you add details to you question, I'll adapt accordingly.
Hook into SelectedIndexChanged event and put your code inside of it
private void lstJoueurs_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstJoueurs.SelectedIndex != -1)
{
btnVoirFiche.Enabled = true;
btnEchangerJoueur.Enabled = true;
}
}
As an alternative, and using mrlucmorin's answer, you could use the listbox's SelectedItem which will return null if nothing is selected.

how can i extract the index of subitems in a listview?

im trying to pass an item from a listview1 to another listview2 and i want to check if the selected item is still not present in listview2. im trying to use a for loop to get each index of listview2 and compare it to the item selected in listview1. i tried using this but an error says that value of 0 is not a valid index.
private void listView1_DoubleClick(object sender, EventArgs e)
{
bool test = true;
for (int i = 0; i < listView1.Items.Count; i++)
{
string ls = listView2.Items[i].SubItems[0].Text;
string ps = listView1.Items[listView1.FocusedItem.Index].SubItems[0].Text;
if (ls.Trim() == ps.Trim())
{
test = false;
}
}
if (test == true)
{
ListViewItem ty = new ListViewItem(listView1.Items[listView1.FocusedItem.Index].SubItems[0].Text);
ty.SubItems.Add(listView1.Items[listView1.FocusedItem.Index].SubItems[1].Text);
listView2.Items.AddRange(new ListViewItem[] { ty });
}
else
{
MessageBox.Show("Student is already present in the list.","Cannot add to list",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}
}
figured it out just as suggested. i used the foreach statement
private void listView1_DoubleClick(object sender, EventArgs e)
{
bool test = true;
string ps = listView1.Items[listView1.FocusedItem.Index].SubItems[0].Text;
foreach(ListViewItem disitem in listView2.Items)
{
string ls = disitem.SubItems[0].Text;
if (ps.Trim() == ls.Trim())
{
test = false;
}}
if (test == true)
{
ListViewItem ty = new ListViewItem(listView1.Items[listView1.FocusedItem.Index].SubItems[0].Text); ty.SubItems.Add(listView1.Items[listView1.FocusedItem.Index].SubItems[1].Text);
listView2.Items.AddRange(new ListViewItem[] { ty });
}
else
{
MessageBox.Show("Student is already present in the list.","Cannot add to list",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}}
I'm trying to pass an item from a listview1 to another listview2 and I
want to check if the selected item is still not present in listview2.
I would simplify your method to something like:
private void listView1_DoubleClick(object sender, EventArgs e)
{
// Get the value of the selected item
string theItem = listView1.SelectedItems[0];
// Add to second list if it's not already in there
if(!listView2.Items.Contains(theItem))
{
listView2.Items.Add(theItem);
}
else
{
MessageBox.Show("Student is already present in the list.","Cannot add to list",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}
}
private void listView1_DoubleClick(object sender, EventArgs e)
{
bool test = true;
var selectedItem = listView1.SelectedItems[0];
foreach(var item in listview2.Items)
{
string listview2Text = item.SubItems[0].Text;
string listview1Text = selectedItem.SubItems[0].Text;
if (listview2Text.Trim() == listview1Text.Trim())
{
test = false;
}
}
if (test == true)
{
//I am not sure exactly what you're trying to do if the test is true but I think you're trying to do this
listView2.Items.Add(selectedItem);
}
else
{
MessageBox.Show("Student is already present in the list.","Cannot add to list",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}
}
I believe it should be something like:
private void listView1_DoubleClick(object sender, EventArgs e)
{
bool add = true;
string selected = listView1.Items[listView1.FocusedItem.Index];
foreach(ListViewItem item in listView2.Items)
if (selected.SubItems[0].Text == item.SubItems[0].Text)
{
add = false;
break;
}
if(add)
listView2.Items.Add(selected);
else
MessageBox.Show("Student is already present in the list.","Cannot add to list",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}
but I am pretty unsure...

C# ListBox Selected Item Null Exception

The user can click an item in a ListBox as follows:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox2.Clear();
listBox2.Items.Clear();
string[] p =
Directory.GetFiles(
textBoxDir.Text,
listBox1.SelectedItem.ToString(),
SearchOption.AllDirectories);
foreach (string open in p)
......
}
All is fine. However if the user clicks on an empty space in the ListBox, it displays the following error:
System.NullReferenceException
This is because of this line of code:
string[] p =
Directory.GetFiles(
textBoxDir.Text,
listBox1.SelectedItem.ToString(),
SearchOption.AllDirectories);
Does anyone have a clever work around? Or suggest an aalternative to my code?
The workaround is to check for a null value, and exit early.
if (listBox1.SelectedItem == null)
{
return;
}
This avoids the nesting introduced by the other answers, which makes the code less readable.
You can check SelectedIndex before that line:
if(listBox2.SelectedIndex < 0)
return;
How about doing a
if(listBox1.SelectedItem != null){
// ... do your work with listBox1.SelectedItem here
}
that should prevent that error from happening.
How about
if (listBox1.SelectedItem != null)
{
string[] p = Directory.GetFiles(textBoxDir.Text, listBox1.SelectedItem.ToString(), SearchOption.AllDirectories);
}
Full Code
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
textBox2.Clear();
listBox2.Items.Clear();
string[] p = Directory.GetFiles(textBoxDir.Text, listBox1.SelectedItem.ToString(), SearchOption.AllDirectories);
foreach (string open in p)
...... }
}
}
just check first if listbox1.SelectedItem is empty or not prior to calling this line:
string[] p = Directory.GetFiles(textBoxDir.Text, listBox1.SelectedItem.ToString(), SearchOption.AllDirectories);
I had a similar problem. This is the shortest way i fixed it.
private void button1_Click(object sender, EventArgs e)
{
radioButton1.Checked = !radioButton1.Checked;
string indicadorPais = "Something";
if (listaPaises.SelectedItem != null)
{
indicadorPais = listaPaises.SelectedItem.ToString();
label1.Text = indicadorPais;
}
As a sidenote. My condition originally was comparing listaPaises.SelectedItem.ToString() != null. This broke because i was casting null to a string. The code im sending works fine.
However none of these allow you to go back in and re-select from the list box. Still working on that issue - will update.
while (user == null) {
try {
user = this.lstAdministratorName.SelectedItem.ToString();
} catch {
lstAdministratorName.ClearSelected();
return;
}
}

How to loop through dropdown items in a toolstrip

I have a dropdown in my toolstrip (toolbar) i have attached a click event to each item in drop down as the dropdown has been populated dynamically, now i can casted the selected item in the dropdown and set its state to checked, to have a tick next to it, i wish to have a loop in another method to check which item has been checked. How do i loop through the items in the dropdown checking which item is checked?
foreach (DataSet1.xspLibraryByNameRow libName in data.xspLibraryByName)
{
var name = new LibraryItems(libName);
if (libName.xlib_Code != "NULL")
{
catDrpDwn.DropDown.Items.Add(name);
catDrpDwn.DropDown.Tag = name;
name.Click += new EventHandler(name_Click);
}
}
}
void mapArea_VE_MapReady(object sender, EventArgs e)
{
loadPoints();
}
void name_Click(object sender, EventArgs e)
{
var selected = (LibraryItems)sender;
selected.Checked = true;
loadPoints();
}
foreach (var items in catDrpDwn.DropDown.Items)
{
var it = (LibraryItems)items;
if (it.Checked == true)
{
}
}
Try this
var items=catDrpDwn.DropDown.Items.Cast<LibraryItems>().Where(d=>d.Checked).ToList();
here you will get all checked items and you can loop into it.

Categories

Resources