I am trying to move items from one list box to another if they are multiple but I am able to move only few, means less than the count. I am not able to implement via for each and for loop as well.
if (AdvLst.SelectedIndex > -1)
{
for (int i = 0; i <= AdvLst.Items.Count - 1; i++)
{
if (AdvLst.Items[i].Selected)
{
string _value = AdvLst.SelectedItem.Value;
string _text = AdvLst.SelectedItem.Text;
ListItem item = new ListItem();
item.Text = _text;
item.Value = _value;
SelectedMortLst.Items.Add(AdvLst.Items[i]);
AdvLst.Items.Remove(AdvLst.Items[i]);
}
}
}
and via foreach loop:
foreach (ListItem li in AdvLst.Items)
{
if (li.Selected == true)
{
SelectedMortLst.Items.Add(AdvLst.SelectedItem);
AdvLst.Items.Remove(AdvLst.SelectedItem);
}
}
Solution 1
var selectedItems = AdvLst.Items.Cast<ListItem>().Where(m => m.Selected).ToArray();
SelectedMortLst.Items.AddRange(selectedItems);
//there's no removeRange, so...
foreach(var item in selectedItems)
AdvLst.Items.Remove(item);
Solution 2 (almost the same)
var selectedItems = AdvLst.Items.Cast<ListItem>().Where(m => m.Selected).ToArray();
foreach(var item in selectedItems) {
SelectedMortLst.Add(item);
AdvLst.Items.Remove(item);
}
Solution 3, for loop code corrected
for (int i = 0; i <= AdvLst.Items.Count - 1; i++)
{
if (AdvLst.Items[i].Selected)
{
string _value = AdvLst.SelectedItem.Value;
string _text = AdvLst.SelectedItem.Text;
ListItem item = new ListItem();
item.Text = _text;
item.Value = _value;
SelectedMortLst.Items.Add(AdvLst.Items[i]);
AdvLst.Items.Remove(AdvLst.Items[i]);
i--;
}
}
cause if you remove an item in the for loop, the count of the collection changes, and the item which is at i+1 place when you remove item has now index i. With i--, your for loop is adapted to that change
Do one operation at a time, either delete or add first.
You may add items to destination list first and removed from the source afterwards
List<ListItem> itemsToDelete=new List<ListItem>();
foreach (ListItem li in AdvLst.Items)
{
if (li.Selected == true)
{
SelectedMortLst.Items.Add(AdvLst.SelectedItem);
itemsToDelete.Add(AdvLst.SelectedItem);
// AdvLst.Items.Remove(AdvLst.SelectedItem);
}
}
foreach(ListItem item in itemsToDelete)
{
AdvLst.Items.Remove(item);
}
Related
I'm trying to modify this code. I need to check for a value in a specific element of FilteredCheckObservable and if true, change the value of another part of that element.
Basically something like
if (FilteredCheckObservable items.Lang = 'ENG')
{items.check = newcheckname;}
Then this will update the sourceGroups Collection.
if (string.IsNullOrEmpty(departmentLine.LineID) || string.IsNullOrEmpty(departmentLine.LineName))
continue;
bool discovered = false;
foreach (var group in sourceGroups)
{
if (!group.Key.Line.IsEqual(departmentLine))
continue;
group.Key.IsDiscovered = true;
discovered = true;
group.Key.ScheduleStatusCount = group.CountGroupItem;
break;
}
if (discovered == false)
{
var _ScheduleItemObservable = new ScheduleItemObservable(departmentLine, MainViewViewModel, Shift.ToString());
var item = new Grouping<ScheduleItemObservable, FilteredCheckObservable>(_ScheduleItemObservable);
if (IsShiftValid)
{
item.Key.Shift = Shift.ToString();
item.Key.IsHistoryEnabled = true;
}
sourceGroups.Add(item);
}
for (int index = 0; index < sourceGroups.Count; index++)
{
if (sourceGroups[index].Key.IsDiscovered == true)
{
foreach (var group in sourceGroups)
{
foreach (FilteredCheckObservable items in group)
{
if (items.Lang_ID == LanguageService.Instance.LanguageType.ToString())
{
sourceGroups.Clear();
sourceGroups.Add(item);
}
}
}
}
}
Welcome Travis,
I would wager the guilty culprit is your foreach loop.
https://stackoverflow.com/a/759985/3403999
You aren't allowed to modify a collection inside of a foreach loop.
I don't know if your collection has an indexer, but if it does, you can convert to a for loop:
for (int i = 0; i < sourceGroups.Count; i++)
{
var group = sourceGroups[i];
// The rest of your code.
I could be wrong. You do say you are trying to modify some existing code. Is it some code that is online? Maybe you could link to it to provide a full context.
Based on your new snippet, you need two for loops:
for (int index = 0; index < sourceGroups.Count; index++)
{
if (sourceGroups[index].Key.IsDiscovered == true)
{
//foreach (var group in sourceGroups)
for (int j = 0; j < sourceGroups.Count; j++)
{
var group = sourceGroups[j];
foreach (FilteredCheckObservable items in group)
{
if (items.Lang_ID == LanguageService.Instance.LanguageType.ToString())
{
sourceGroups.Clear();
sourceGroups.Add(item);
}
}
}
}
}
^ Although that might still be a bad loop. Primarily because you have sourceGroups.Clear();.
What you might be better off doing is creating an internal collection called say 'results'. Do your loop looking for your conditions, and if they meet, add that item to the results collection.
Once your loops terminate, then call sourceGroups.Clear(), and then sourceGroups.AddRange(results). If sourceGroups doesn't have an AddRange, then one final loop of:
foreach (var group in results) { sourceGroups.Add(group); }
The comboBox9 gets populated with unique values from an Excel Range with the code below.
comboBox9.Items.Clear();
HashSet<string> distinct = new HashSet<string>();
foreach (_Excel.Range cell in range.Cells)
{
string value = (cell.Value2).ToString();
if (distinct.Add(value))
comboBox9.Items.Add(value);
}
What i tried to do unsuccessfully is set the index of the combobox9 with the first item that satisfies the if condition .
foreach (string item in comboBox9.Items)
{
if (278 * Variables.m3h / (Math.Pow(int.parse(item) / 2, 2) * 3.14) > Variables.maxvelocity)
{
comboBox9.SelectedIndex = comboBox9.Items.IndexOf(item);
}
}
Any ideas on where i'm going wrong ?
All items match the condition will be selected. Because the selection unique, the last selected item is displayed.
When the first item is selected, you need stop the selection :
foreach (int item in comboBox9.Items)
{
if (278 * Variables.m3h / (Math.Pow(item / 2, 2) * 3.14) > Variables.maxvelocity)
{
comboBox9.SelectedIndex = comboBox9.Items.IndexOf(item);
break; // a item is selected, then stop the selection
}
}
I think your code might get an exception of "Specified cast is not valid" in the line of
comboBox9.SelectedIndex = comboBox9.Items.IndexOf(item); because you are adding the items in comboBox9 as "string" type and using "int" type in foreach (int item in comboBox9.Items). So, Please Check your code. I am going to paste 2 different codes below both for int type and string type.
//FOR INT TYPE
void ComboLoadAndSelectIndex()
{
comboBox9.Items.Add(1);
comboBox9.Items.Add(10);
comboBox9.Items.Add(20);
foreach (int item in comboBox9.Items)
{
if (item == 10)//your math Condition
{
comboBox9.SelectedIndex = comboBox9.Items.IndexOf(item);
}
}
}
//FOR String Type
void ComboLoadAndSelectIndex()
{
comboBox9.Items.Add(1.ToString());
comboBox9.Items.Add(10.ToString());
comboBox9.Items.Add(20.ToString());
foreach (string item in comboBox9.Items)
{
if (item == 10.ToString())//your math Condition
{
comboBox9.SelectedIndex = comboBox9.Items.IndexOf(item);
}
}
}
NOTE: Both codes are works fine in Winforms Application. Please check and try it.
Figured it out :
comboBox9.Items.Clear();
HashSet<string> distinct = new HashSet<string>();
foreach (_Excel.Range cell in range.Cells)
{
string value = (cell.Value2).ToString();
if (distinct.Add(value))
comboBox9.Items.Add(value);
}
if (comboBox9.Items.Count > 1)
{
foreach (string item in comboBox9.Items)
{
if (278 * Variables.m3h / (Math.Pow(int.Parse(item) / 2, 2) *
3.14) < Variables.maxvelocity)
{
comboBox9.SelectedIndex = comboBox9.Items.IndexOf(item);
break;
}
}
}
else
{
comboBox9.SelectedIndex = -1;
}
I have a list of postcodeitems and I bind this to a listbox.
It contains two properties : postcode, area.
I want to loop through the listbox items and if the item is selected, add the postcodeitem object to another list.
List<Valueobjects.postcodeitem> temp = _BL.GetPostCodeAreasFromZones();
PCList.AddRange(temp);
ListBox1.DataSource = PCList;
ListBox1.DataBind();
List<Valueobjects.postcodeitem> postcodecollection = new List<Valueobjects.postcodeitem>();
foreach (ListItem listitem in ListBox1.Items)
{
if (listitem.Selected)
{
i = i + 1;
//Run at 20 to speed up query
if (i == 20)
{
//Get data
CustList.AddRange(BL.SearchCustomerByPostcodeArea(postcodecollection,2));
i = 0;
}
else
{
//add the post code to temp list
postcodecollection.Add(listitem);
}
}
}
if (i > 0)
{
//get data
CustList.AddRange(BL.SearchCustomerByPostcodeArea(postcodecollection,2));
}
}
Obviously where I am trying to add (listitem) isnt going to work as this is a list item and not a postcodeitem. My question is how do I get the postcodeitem object within the list where the list item is selected?
thanks
Try something like following.
IList<Employee> boundList = ListBox1.DataSource
var obj = boundList[ListBox1.SelectedIndex]
Update => I have not tested the code but something like following. Using for loop to track the element index.
for (int i = 0; i< ListBox1.Items.Length; i++)
{
if (ListBox1.Items[i].Selected)
{
i = i + 1;
//Run at 20 to speed up query
if (i == 20)
{
//Get data
CustList.AddRange(BL.SearchCustomerByPostcodeArea(postcodecollection,2));
i = 0;
}
else
{
//add the post code to temp list
postcodecollection.Add(ListBox1.DataSource.ToList().ElementAt(i));
}
}
}
if (i > 0)
{
//get data
CustList.AddRange(BL.SearchCustomerByPostcodeArea(postcodecollection,2));
}
}
Anyways this is not recommended way. You should get selected value and use that selected value(unique field) to fetch relevant data from any persistant storage like database.
I'm trying to select values in a CheckBoxList control based on a data source. I have five items in the CheckBoxList and three items in the data source, but in the loop I only get one item selected.
if (ddlUserId.SelectedIndex != 0)
{
RoleDetails rd;
rd = CatalogAccess.GetSingleUserRole(ddlUserId.SelectedValue.ToString());
for (int i = 0; i < cblRoles.Items.Count; i++)
{
cblRoles.Items.FindByValue(rd.RoleID.ToString()).Selected = true;
}
}
I tried this, but it still selects only one item:
RoleDetails rd;
for (int i = 0; i < cblRoles.Items.Count; i++)
{
rd = CatalogAccess.GetSingleUserRole(ddlUserId.SelectedValue.ToString());
if (cblRoles.Items[i].Value == rd.RoleID.ToString())
cblRoles.Items[i].Selected = true;
}
CheckboxList bind code
cblRoles.DataSource = CatalogAccess.GetRoles();
cblRoles.DataTextField = "RoleDetails";
cblRoles.DataValueField = "RoleId";
cblRoles.DataBind();
When you use for loop you need to use index value (Here it is "i"), like
for (int i = 0; i < cblRoles.Items.Count; i++)
{
if(cblRoles.Items[i].Value == rd.RoleID.ToString())
cblRoles.Items[i].Selected = true;
}
Or you can use foreach as below:
Here i have created looping through items of checkbox list using foreach & item will be made selected id its value will match RoleId .
foreach (ListItem li in cblRoles.Items)
{
if (rd.RoleID.ToString() == li.Value)
{
li.Selected = true;
}
else
{
li.Selected = false;
}
}
The controls (ListItems) are created dynamically, so there is no possibility to sort pre-insertion.
I've attempted a solution, which does the job (sort on a list then reconstructing the control) but I would like a more elegant solution.
For the sake of completeness below is my current solution:
List<ListItem> lli = new List<ListItem>();
foreach (ListItem item in cblGIFFlags.Items) lli.Add(item);
cblGIFFlags.Items.Clear();
bool sorting = true;
while (sorting)
{
sorting = false;
for (int i = 0; i < lli.ToArray().Length - 1; i++)
{
ListItem x = lli[i];
ListItem y = lli[i + 1];
if (Comparer<String>.Default.Compare(x.Text,y.Text) > 0)
{
lli[i] = y;
lli[i + 1] = x;
sorting = true;
}
}
}
foreach (ListItem item in lli) cblGIFFlags.Items.Add(item);
Since ListItemCollection implements IEnumerable, I thought maybe I could cast to IEnumerable<ListItem> or something. I couldn't figure out how to do that cast. Here's the best I could come up with:
var items = new List<ListItem>();
foreach (ListItem item in listBox.Items) items.Add(item);
listBox.Items.Clear();
listBox.Items.AddRange(items.OrderBy(i=>i.Value).ToArray());