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);
}
}
Related
I have a DataGridView with CheckBox column, my question is how do I get the data next to a checked checkboxes and assign them to a variables in array?
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
if (Convert.ToBoolean(this.dataGridView1.Rows[e.RowIndex].Cells["chkBoxColumn"].Value = true) == true)
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString());
}
}
}
It prints the last checked item over and over.
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (bool.Parse(dataGridView1.Rows[i].Cells["chkBoxColumn"].Value.ToString()) == true)
{
MessageBox.Show(dataGridView1.Rows[i].Cells[1].Value.ToString());
}
}
}
and i'm getting a null reference exception using this.
Edit
Question got changed, so tweaked the code so that the values get put into a list.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
List<string> someList = new List<string>();
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
var cell = row.Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
if (Convert.ToBoolean(cell.Value) == true)
{
if (cell.State != DataGridViewElementStates.Selected)
{
someList.Add(row.Cells[1].Value.ToString();
}
}
else if (cell.State == DataGridViewElementStates.Selected)
{
someList.Add(row.Cells[1].Value.ToString();
}
}
}
This might do the trick for you, however you'll get a popup every time a user ticks a checkbox, and you'll get as many popup as there are checkboxes that are true.
the problem is in the line
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString());
e.RowIndex points to the changed row
it should be:
for (int i = 0; i <= this.dataGridView1.Rows)
{
var row = this.dataGridView1.Rows[i]
if (Convert.ToBoolean(this.dataGridView1.Rows[i].Cells["chkBoxColumn"].Value = true) == true)
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString());
}
}
Also, note that you're getting error in your second example because some row is containing a null value in the checkbox column.
Convert.ToBoolean(null) returns false
But bool.Parse(null) throws an exception
I guess something like this ?
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
Stringbuilder text = new StringBuilder();
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
if (Convert.ToBoolean(row.Cells["chkBoxColumn"].Value = true) == true)
{
text.Append(row.Cells[1].Value.ToString());
}
}
MessageBox.Show(text.ToString());
}
EDIT: the question has changed from showing the values to saving them into an array, so I need to change my answer also
Suppose you want all values for Cell[1] saved into an array
and suppose that cell is of type integer.
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
List<int> list = new List<int>();
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
if (Convert.ToBoolean(row.Cells["chkBoxColumn"].Value = true) == true)
{
list.Add(int.Parse(row.Cells[1].Value.ToString()));
}
}
// you now have all values saved into the list
}
You can put the code in a button click and find checked values this way:
private void button1_Click(object sender, EventArgs e)
{
var checkedValues = dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(row => (bool?)row.Cells["Your CheckBox Column Name"].Value == true)
.Select(row => string.Format("{0}", row.Cells["The Other Column Name"].Value))
.ToList();
MessageBox.Show(string.Join(",", checkedValues));
}
So I have a button, where if you click it, it adds "Candy" to a listbox, how do I make it so, if another item with the same name is being added, instead of adding it in a new line, update the first line to show x2, 3, 4, etc. Is that possible or would I have to make another Listbox and match the index? I've tried the following with another listbox and an int variable.
private void btnCandy_Click(object sender, EventArgs e)
{
lstProducts.Items.Add("Candy");
foreach (var item in lstProducts.Items)
{
if (item.ToString() == "Candy")
{
++Productcount;
lstQuantity.Items.Add(Productcount);
if (Productcount > 1)
{
lstQuantity.Items.Insert(lstProducts.Items.IndexOf("Candy"), Productcount);
}
}
}
}
using System.Text.RegularExpressions;
Use:
private void btnCandy_Click(object sender, EventArgs e)
{
string query = "Candy";
bool isExist = false;
for (int i = 0; i < lstProducts.Items.Count; i++)
{
var s = lstProducts.Items[i].ToString();
if (s.StartsWith(query))
{
if (s == query)
{
lstProducts.Items[i] = query + "x2";
isExist = true;
break;
}
else
{
// Escape your plain text before use with regex
var pattern = Regex.Escape(query);
// Check if s has this formnat: queryx2, queryx3, queryx4, ...
Match m = Regex.Match(s, "^" + pattern + #"x(\d+)$");
if (m.Success)
{
lstProducts.Items[i] = query + "x" + (Int32.Parse(m.Groups[1].Value) + 1);
isExist = true;
break;
}
}
}
}
if (!isExist) lstProducts.Items.Add(query);
}
Note:
\d mean any digit (0 - 9)
I'd try to iterate through listbox items and if I find "Candy" then take that index and update title.
private void btnCandy_Click(object sender, EventArgs e)
{
bool found = false;
foreach (var item in lstProducts.Items)
{
if (item.ToString().StartsWith("Candy"))
{
// update item title
found = true;
break; // no need to continue
}
}
if(!found)
{
lstProducts.Items.Add("Candy");
}
}
this way you are not going to add duplicates
Here is some pseudo-code to help you. Add this to your button click event:
int i = 0;
foreach (string item in listbox1.Items)
{
If (item == textbox1.text) //textbox1.text contains the string such as 'candy'
{
i++;
listbox1.Items.Remove(item);
listbox1.Items.Add(textbox1.text + " " + i.ToString());
}
}
You may have to reset the counter as needed.
Am trying to delete textboxes and labels while their names which have equal value from the selected items from the listbox. If i run this code only the first if statement is executed and removing only the label controls inside the table.
I must also mention that controls of the table are dynamically created.
private void pictureBox2_Click(object sender, EventArgs e)
{
for (int i = 0; i < listBox2.SelectedItems.Count; i++)
{
foreach (Control t in table2.Controls)
{
if (t is Label && t.Text==listBox2.SelectedItem.ToString())
{
table2.Controls.Remove(t);
continue;
}
if (t is TextBox && t.Name.Contains(listBox2.SelectedItem.ToString()))
{
table2.Controls.Remove(t); continue;
}
}
listBox2.Items.Remove(listBox2.SelectedItems[i]); i--;
}
}
This is how controls are created indide the table.
private void pictureBox1_Click(object sender, EventArgs e)
{
listBox2.Items.Clear();
this.table2.Controls.Clear();
foreach (var item in listBox1.SelectedItems)
{
table2.Controls.Add(new Label() { Name = item.ToString(), Text = item.ToString(), AutoSize = true });
table2.Controls.Add(new TextBox() { Name = item.ToString(), AutoSize = true });
}
}
}
When you remove an item from a collection (suppose the item at position 0), the item at the next position (postion 1) shifts in position zero. But your for loop execute the next iteration and your indexer becomes 1 and so it terminate the loop.
The first approach to avoid this is to loop in reverse order, from the end of the collection toward the begin of it
But you could also simplify a lot your code with
private void pictureBox2_Click(object sender, EventArgs e)
{
for (int i = listBox2.SelectedItems.Count - 1 ; i >= 0 ; i--)
{
// This is our search term...
string curItem = listBox2.SelectedItems[i].ToString();
// Get only the controls of type Label with Text property equal to the current item
var labels = table2.Controls
.OfType<Label>()
.Where (c => c.Text == curItem)
.ToList();
if(labels != null)
{
for(int x = labels.Count()-1; x >= 0; x--)
table2.Remove(labels[x]);
}
// Get only the controls of type TextBox with Name property containing the current item
var boxes = table2.Controls
.OfType<TextBox>()
.Where (c => c.Name.Contains(curItem)
.ToList();
if(boxes != null)
{
for(int x = boxes.Count()-1; x >= 0; x--)
table2.Remove(boxes[x]);
}
listBox2.Items.Remove(curItem);
}
}
Why are you decrementing your iterator at the end of your for loop? It looks like you're stuck in the loop, buddy.
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
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;
}
}