loop through checkedListBox items without the select all item - c#

I want to get the items from a checkedListBox into a List<>, but without the select all/ deselect all (first checkbox)..can't figure it out how to not add the first item..
this is the code:
foreach (string s in checkedListBoxDepts.CheckedItems)
{
if (checkedListBoxDepts.SelectedItems.IndexOf(s) == 0)
continue;
list.Add(s);
}
then I take the items and put in another list to avoid errors:
foreach (string s in list)
{
list2.Add(s);
}
but still the select all is loaded...help

Try:
foreach (var s in checkedListBoxDepts.CheckedItems)
{
if (checkedListBoxDepts.IndexOf(s) == 0)
continue;
list.Add(s.ToString());
}

foreach (string s in checkedListBoxDepts.CheckedItems)
{
if (checkedListBoxDepts.SelectedItems.IndexOf(s) == 0)
continue;
list.Add(s);
}
after that remove first item from list
list.removeat(0);

Related

Asp.NET drop down list adding list items from list in a form of a tree

I have a method in which I have to populate dropdownlist from a collection that is formed like a tree. I have list of parent Objects, every parent can have list of child Objects, every child can have list of grandchild Objects and so on.
I have to loop through tha collection because I want to indent items so hierarchy is built.
ddl should look like this:(- is symbol for indent)
parent
-child
--grandchild
---grandgrandchild
-child
parent
..and so on..
How should I go about changing this method so i dont have loop inside a loop inside a loop, asume I dont know the depht of a tree
Thanks in advance!
Method:
private void BindObjectDropDown()
{
ddlObject.Items.Clear();
ObjectCollection collection = Object.GetList();
if (collection != null && collection.Count > 0)
{
foreach (var parent in collection)
{
ddlObject.Items.Add(new ListItem($"{parent.Title}", parent.Id.ToString()));
if (parent.Objects != null && parent.Objects.Count > 0)
{
foreach (var child in parent.Objects)
{
ddlObject.Items.Add(new ListItem($"{_ddlIndent}{child.Title}", child.Id.ToString()));
if (child.Objects != null && child.Objects.Count > 0)
{
foreach (var grandchild in child.Objects)
{
ddlObject.Items.Add(new ListItem($"{_ddlIndent}{_ddlIndent}{grandchild.Title}", grandchild.Id.ToString()));
//and so on and so on ....
}
}
}
}
}
foreach (ListItem item in ddlObject.Items)
{
item.Text = HttpUtility.HtmlDecode(item.Text);
}
}
}
If someone wants a solution, recursion, of course:
private void BindMyObjectDropDown()
{
ddlMyObject.Items.Clear();
MyObjectCollection collection = MyObject.GetList(0, true);
if (collection != null && collection.Count > 0)
{
AddDdlItems(collection, 0);
foreach (ListItem item in ddlMyObject.Items)
{
item.Text = HttpUtility.HtmlDecode(item.Text);
}
}
ddlMyObject.Items.Insert(0, new ListItem(EntityResource.DefaultDropDownPick, "0"));
}
private void AddDdlItems(MyObjectCollection collection, int depth)
{
string indent = string.Empty;
for (int i = 0; i < depth; i++)
{
indent += _ddlIndent;
}
foreach (var myObject in collection)
{
ddlMyObject.Items.Add(new ListItem($"{indent}{myObject.Title}", myObject.Id.ToString()));
if (myObject.Objects!= null && myObject.Objects.Count > 0)
{
AddDdlItems(myObject.Objects, depth + 1);
}
}
}

How can I iterate through an array and skip any empty items?

I have taken a csv, made from an excel file, and put it into a data table. There are cells from the excel csv file that are empty and when I iterate through them, they are also iterated through. I wish to not iterate over them.
foreach (DataRow datarow in sorted.Rows)
{
Boolean first = true;
Console.Write(Environment.NewLine);
foreach (var item in datarow.ItemArray)
{
if (item != null)
{
int i = 0;
if (first)
first = false;
else
Console.Write(",");
Console.Write(item);
}
else
break;
}
}
I have tried the above and it still iterates through the empty cells.
Expanding on JohnD answer, you can try this, assuming you only want to output the fields to the Console:
var text = string.Empty;
foreach (DataRow datarow in sorted.Rows)
{
var items = datarow.ItemArray
.Where(x => ((x != null) && !string.IsNullOrEmpty(x.ToString())));
var textJoined = string.Join(",", items);
text += textJoined + Environment.NewLine;
}
Console.WriteLine(text);
You may not be familiar with LINQ, so you will need the following using statement:
using System.Linq;
Again this solution assumes you only want to output the values to the console window, it does not assume you want to iterate through all the columns for a given row. If that is what you want let me know and I can make the appropriate modifications
[edit]
whoops just re-read your question and it appears you do want to iterate through each column, so here is a solution below:
var text = string.Empty;
foreach (DataRow datarow in sorted.Rows)
{
var items = datarow.ItemArray
.Where(x => ((x != null) && !string.IsNullOrEmpty(x.ToString())));
var currentLine = string.Empty;
foreach(var item in items)
{
// do something with item
// in this case append to currentLine
currentLine += item + ",";
}
text += currentLine.Substring(0, currentLine.Length - 2) + Environment.NewLine;
}
Console.WriteLine(text);
You get the same result, you can now just do what you need for each item
Assuming that the item is really a string, check to see if item is null or empty using String.IsNullOrEmpty().
if (item != null && !String.IsNullOrEmpty(item.ToString()))
Additionally, replace the break statement with a continue
Why not like this?
// ItemArray is object[]
foreach (var item in datarow.ItemArray)
{
if (first)
{
first = false;
}
else
{
// I think you are expecting to see the comma here even the previous element is empty e.g. A,B,,D (that missing C)
Console.Write(",");
}
// so here we cannot guarantee "if (item is string)"
if (item != null)
{
Console.Write(item.ToString());
}
}
(My habit to wrap all codes in {})
foreach (DataRow datarow in sorted.Rows)
{
Boolean first = true;
Console.Write(Environment.NewLine);
foreach (var item in datarow.ItemArray)
{
if (!string.IsNullOrEmpty((item ?? "").ToString()))
{
int i = 0;
if (first)
first = false;
else
Console.Write(",");
Console.Write(item);
}
else
continue;
}
}

How to skip listitem with index 0 foreach checkboxlist item

I have a CheckBoxList which I am going through all its items using:
foreach (ListItem item in this.checklist.Items)
I was wondering how I can skip the first item in this CheckBoxList(item with index 0).
Linq should help you do the trick. Make sure to cast the items collection to typed collection, and then you can use Skip to skip first item:
foreach (ListItem item in this.checklist.Items.Cast<ListItem>().Skip(1))
I believe one way to do this is:
bool isFirst = true;
foreach (ListItem item in this.checklist.Items)
{
if (isFirst) {
isFirst = false;
} else {
// do checking
}
}
Try this.
foreach (ListItem item in this.checklist.Items)
{
if (item != this.checklist.Items[0]) {
// Do something
}
}

Check Box list collection was modified enumeration operation may not execute

I have seen lots of examples in this Question, but till not concluded. and i tried with all these EXAMPLES. I am trying to remove empty check box list which are binding from data base.
DataSet ds4 = getCheckBox(ViewState["id"].ToString());
chkEnvironment.DataSource = ds4;
chkEnvironment.DataTextField = "Environment";
chkEnvironment.DataValueField = "Environmentid";
chkEnvironment.DataBind();
But it is showing empty check boxes in my page. how to do it
protected void chkEnvironment_DataBound(object sender, EventArgs e)
{
foreach (ListItem item in chkEnvironment.Items)
{
if (item.Value == "NULL")
{
chkEnvironment.Items.Remove(item);
}
}
}
You cannot modify a collection during enumeration. You could store the items you want to remove later:
var itemsToRemove = new List<ListItem>();
foreach (ListItem item in chkEnvironment.Items)
{
if (item.Value == "NULL")
{
itemsToRemove.Add(item);
}
}
foreach(var item in itemsToRemove)
chkEnvironment.Items.Remove(item);
the same with LINQ:
var itemsToRemove = chkEnvironment.Items.Cast<ListItem>()
.Where(i => i.Value == "NULL")
.ToList();
foreach(var item in itemsToRemove)
chkEnvironment.Items.Remove(item);

Removing more than 1 item in listbox

please help me how can remove more than 1 item in a listbox.I know the code for removing 1 item: listbox.Items.RemoveAt(i)
but for more than 1 item selected in a listbox,what is the code? write the code for example in button-click event.I have only a button and a listbox in my winform.(write codes in C#)
while(listbox.SelectedItems.Count > 0)
{
listbox.Items.Remove(listbox.SelectedItem);
}
ListBox1.ClearSelection();
//or
foreach (ListItem listItem in ListBox1.Items)
{
listItem.Selected = false;
}
List<ListItem> itemsToRemove = new List<ListItem>();
foreach (ListItem listItem in ListBox1.Items)
{
if (listItem.Selected)
itemsToRemove.Add(listItem);
}
foreach (ListItem listItem in itemsToRemove)
{
ListBox1.Items.Remove(listItem);
}

Categories