i'm trying to check each item in a checkedlistbox and do something with the item depending if it is checked or not. I've been able to just get the checked items with the indexCollection, but i'm having trouble getting all of the items, i'm getting this error 'Unable to cast object of type 'System.String' to type 'System.Windows.Forms.ListViewItem'
foreach (ListViewItem item in checkedListBox2.Items)
{
if (item.Checked == true)
//do something with item.name
else
//do something else with item.name
}
i'm unsure why it's giving me the string cast error in the foreach line. How can I accomplish this? Thanks.
If you allow a checkbox to have the Indeterminate state then you should use the GetItemCheckState method to retrieve the state of a check box
for (int i = 0; i < checkedListBox2.Items.Count; i++)
{
CheckState st = checkedListBox2.GetItemCheckState(checkedListBox2.Items.IndexOf(i));
if(st == CheckState.Checked)
....
else if(st == CheckState.Unchecked)
....
else
... // inderminate
}
otherwise is enough to call GetItemChecked that return a true/false value (true also for the indeterminate state)
CheckedListBox.Items holds the collection of objects, not the collection of ListViewItem
You can check it this way
for (int i = 0; i < checkedListBox2.Items.Count; i++)
{
if (checkedListBox2.GetItemChecked(i))
{
//do something with checkedListBox2.Items[i]
}
else
{
//do something else with checkedListBox2.Items[i]
}
}
If you allow a checkbox to have the Indeterminate state then you should use the GetItemCheckState method to retrieve the state of a check box
for (int i = 0; i < checkedListBox2.Items.Count; i++)
{
CheckState st = checkedListBox2.GetItemCheckState(i);
if(st == CheckState.Checked)
....
else if(st == CheckState.Unchecked)
....
else
... // inderminate
}
otherwise is enough to call GetItemChecked that return a true/false value (true also for the indeterminate state)
Related
I have a function who's body looks a lot like this:
if (contains(array, element1) > -1){
// do something
} else if (contains(array, element2) > -1) {
// do something
} else if (contains(array, element3) > -1) {
// do someting
}...
The function contains will loop through my array and check to see if it contains an element that I pass to it and return either its position if it exists, or -1 if it doesn't.
In my // do something portion, I need the position of this element in the array. There are a couple of different ways I can do this:
I can call my contains() function once more to get the position.
I can define several variables that are defined as the return of the contain function, and then check them in my if-else block. So something like:
int element1Loc = contains(array, element1);
int element2Loc = contains(array, element2);
int element3Loc = contains(array, element3);
if (element1Loc > -1){
// do something
} else if (element2Loc > -1) {
// do something
} else if (element3Loc > -1) {
// do someting
}...
I can perhaps modify contain to return an int array[2], with array[0] equal to 0 or 1 whether the element is in it or not, and then array[1] qwould equal the actual location, making the code look like thiss:
if (contains(array, element1)[0] > -1){
// do something
} else if (contains(array, element2)[0] > -1) {
// do something
} else if (contains(array, element3)[0] > -1) {
// do something
}...
I can say screw the if-else block, save the return of contains in a variable and run several if-statements.
Solution one will search through my array at least twice. Solution two will search at least as many times as there are elements I'm looking for. Solution 3 is perhaps the best, but maybe not the most elegant. Solution 4 will run each if statement...
What is the best way to search just once? Should I make a function that takes all the things I am looking for and returns an array with the position of each element? Am I overthinking it?
I would modify contains to only use the return value to indicate the error/success of the find, and, if the parameter was found, output the parameter by reference.
int contains(int *data, int value, int *loc)
{
for(int i = 0; i < SIZE; i++)
{
if(data[i]==value)
{
*loc = i;
return 1; // success
}
}
*loc = -1;
return 0; // failure
}
Now, you can just do:
int elem1loc, elem2loc, elem3loc;
if(contains(data, val1, &elem1loc))
// use elem1loc...
if(contains(data, val2, &elem2loc))
// use elem2loc...
You could pass a pointer to say int which would be populated when the contains function finds an element. Then inside your if block you would be assured that pos is the correct index.
Example:
int pos;
if (contains(array, element1, &pos) > -1) {
// Here you can check pos for the position
} else if (contains(array, element2, &pos) > -1) {
// Here you can check pos as well...
}
Here's a solution that doesn't require you to modify contains at all:
int pos;
if ((pos = contains(array, element1)) > -1) {
// do something with pos
} else if ((pos = contains(array, element2)) > -1) {
// do something with pos
} else if ((pos = contains(array, element3)) > -1) {
// do something with pos
}
This works because variable assignment in most imperative languages is an expression.
I am trying to get out of a while loop using C, but using breaks, returns or changing the while condition are not working.
Basically, I want to know why in the last else if, when I state back = true my code keeps entering the for.
I would expect an output like: enter1, enter1, enter1, enter1, enter2.
Instead, the output is something like enter1, enter1, enter1, enter2, enter2, enter2, enter1, enter1, enter1....
This is my code work:
void SolveMap8(Core* core_building, Building* new, Stack* solve, bool goingBack){
Core* coreBuilding = core_building;
Building* first = new -> linked[0];
Building* next = NULL;
bool back = goingBack;
while (back == false) {
for (int i = 0; i < (first -> zone -> building_count); i++) {
if (first -> zone -> buildings[i] != NULL) {
if (first != first -> zone -> buildings[i]) {
next = first -> zone -> buildings[i];
if(next -> color == coreBuilding -> buildings[0] -> color && !city_client_is_taken(next)) {
puts("enter0");
Building_Pair* newPair = Building_Tuple_Create(first, next);
stack_push(solve, newPair);
city_client_link(first, next);
break;
}
else if(!city_client_is_taken(next)) {
if (city_client_is_blank(next)) {
if (!(next -> cored)) {
puts("enter1");
Building_Pair* newPair = Building_Tuple_Create(first, next);
stack_push(solve, newPair);
city_client_link(first, next);
SolveMap8(coreBuilding, next, solve, false);
}
}
}
else if (city_client_is_taken(next)) {
if (i == first -> zone -> building_count - 1) {
puts("enter2");
back = true;
}
}
}
}
}
}
}
Update Sorry, missed the recursion. In that case your problem has nothing to do with a missing break statement, but that you are trying to escape from a for loop at a different scope than you are currently in. You will need special logic to handle a global "done" condition. Perhaps something like this:
void process(Core* core, bool& done) {
for (int i = 0; i < core->size() && !done; ++i) {
if (!core[i]->is_taken()) {
process(core[i], done);
} else if (core[i]->is_taken() {
// done procesing
done = true;
}
}
}
// use via
bool done = false;
process(myCore, done);
In the version you have, the goingBack flag is passed by value, so every function gets its own copy and there is no way to pass the value of back to the parent in the recursive call chain. In my code above, done is passed as a reference, so changing the value at some point in the recursion chain will make it visible at parent scope (because the scope of the variable is outside the function itself). Hope this is more helpful.
I'm trying to compare the X value of two points in two different arrays. Problem is sometimes the value I'm comparing may not exist yet and I'm not entirely sure how to go about making this check before I call upon this variable.
My code looks like this
if (blueShipPositions[0].x == redShipPositions[0].x) {
trace("Match in" + blueShipPositions[0]);
}
The x value for any given point in this array tops out at 4 so the error I'm running into looks like this
if (blueShipPositions[0].x == redShipPositions[4].x) {
trace("true");
}
If redShipPositions[4].x does not exist yet I get an error.
I am aware of the IndexOf function, I just don't know how to apply it here.
Wrap it inside an IF statement that determines the size of an array:
if (redShipPositions.length >= 5) {
if (blueShipPositions[0].x == redShipPositions[4].x) {
trace("true");
}
}
Another way is to have an int local variable to indicate the size of the array:
myArraySize = redShipPositions.length;
then you can use it as an indicator/(stop point) to safely execute your code w/o the concern of IndexOutOfBound exception.
As answer to your question, take this example : (comments inside)
var array:Array = new Array(1, 5, 6, 55)
var index:Number = 3
// type of the elements of array, in this case is Number
var element_type:* = Number
// so to verify if the array[index] exists, we can use
if(array[index]) {
trace(array[index])
}
// or
if(array[index] != undefined) {
trace(array[index])
}
// or
if(array[index] != null) {
trace(array[index])
}
// or
if(typeof array[index] != 'undefined') {
trace(array[index])
}
// or
if(array[index] is element_type) {
trace(array[index])
}
// or
if(array[index] as element_type != null) {
trace(array[index])
}
// or
// here you have to put in the mind that arrays in ActionScript starts always from the index 0, thats why we use < and not <=
if(index < array.length) {
trace(array[index])
}
// we use array.indexOf to search an element and not an index
if(array.indexOf(55)){
trace('we have "55" in this array')
} else {
trace('we don\'t have "55" in this array')
}
For more details about AS3 Array object, take a look here : Adobe.com : AS3 Array.
Hope that helps you.
This is a method where I am using the while loop. I strongly suspect that an infinite loop is possible. How to check and eliminate that?
I am using two while loops here. Sould I totally dismantle the while loop?
public class ReferenceListSaveHandler
{
public PublishReferenceListUpdates populateResponse(SearchQueryResponse pSearchQueryResponse,SearchQueryResponse pListResponse, ObjectFactory objFactory) throws IOException, ParserConfigurationException, SAXException,SipException, Exception
{
ReferenceDataProcessor lRefPro = new ReferenceDataProcessor();
PublishReferenceListUpdates lResponse = null;
Record listRecord = null;
ReferenceDataListItemListType lReferenceDataListItemListType = objFactory
.createReferenceDataListItemListType();
ReferenceDataListType lReferenceDataListType = null;
ReferenceDataListItemType lReferenceDataListItemType = null;
boolean ifSynonym = false;
String lRowIdObject = null;
final int lRowIdLength = 14;
if (refListItemItr.hasNext())
{
Record record = (Record)refListItemItr.next();
boolean continueProcessing = true;
boolean lastRecord = false;
while (continueProcessing)
{ // first use of while loop
if (refListItemItr.hasNext() || lastRecord)
{
continueProcessing = true;
lastRecord = false;
}
else
{
continueProcessing = false;
}
if (continueProcessing)
{
lSynonymListType = objFactory
.createSynonymListType();
Field itemLSIDField = record
.getField(ReferenceDataConstants.FIELD_COMPOUND_ASSET_ID);
if (itemLSIDField == null)
{
continue;
}
else
{
currentItemLSID = itemLSIDField
.getStringValue().trim();
}
lReferenceDataListItemType = objFactory
.createReferenceDataListItemType();
lReferenceDataListItemType = setListDetails(record,
lReferenceDataListItemType,
lId, lName, objFactory);
while (refListItemItr.hasNext()
&& continueProcessing)
{ // second use of while loop
SynonymType lSynonymType = null;
if (continueProcessing)
{
if (lSynonymType != null)
lSynonymListType.getSynonym().add(lSynonymType);
}
}
continueProcessing = true;
}
}//while loop
}
}
}
Please help.
Problem number one: refListItemItr, whatever that is (its definition is not shown), has a .next() method but it's never called inside the loop.
Problem number two: The second while loop is always infinite if you enter it:
while (refListItemItr.hasNext()
&& continueProcessing)
{
SynonymType lSynonymType = null;
if (continueProcessing)
{
if (lSynonymType != null)
lSynonymListType.getSynonym().add(lSynonymType);
}
}
Neither refListItemItr.hasNext(), nor continueProcessing can change inside this loop. That's why it's an infinite loop.
EDIT:
I can't tell you how to change the code because there are many possible ways to change it, depending on what's supposed to happen. You can try this but it may or may not work:
Remove the second loop entirely (it does nothing right now).
Add this line just before the end of the first loop:
record = (Record)refListItemItr.next(); // ADD THIS LINE
} //while loop BEFORE THIS LINE
This is an infinit loop , the outer loop depends on lastrecord which is not beeing set to true anywhere in the program
I throw in a loop counter whenever I write the word while, like this:
int loopCounter = 0, maxLoops = 1000; //just an example
while((loopCounter++) < maxLoops && (myConditions))
{
// loop away, this can't ever be infinite
}
or this
int loopCounter = 0, maxLoops = 1000; //just an example
do
{
// loop away, this can't ever be infinite
}
while((loopCounter++) < maxLoops && (myConditions))
Of course, maxLoops is always sized to be orders of magnitude greater than any reasonable number of iterations... Then I add a check:
if (loopCounter == maxLoops) { throw new InvalidOperationException("Infinite loop detected!"); }
I have an array of objects, each object has a function that returns a Boolean value. What I need to do, is have a loop continuously running until each object returns a true value when the function is called on each object.
EDIT: Sorry I wasn't clear enough, I meant that I want the loop to break, when ALL of the objects functions return true.
Any ideas?
Java style syntax:
boolean good;
while (true) {
good = true;
foreach (MyObject o : myArray) {
if (!o.someFunction()) {
good = false;
break;
}
}
if (good) break;
}
I interpreted it as meaning that every object needed to have its function evaluated to true each time, and once they all evaluate to true break out of the loop.
If I got your question, you can do like this...
do
{
test = 0;
for(all functions)
{
char test_array[] = function_call();
}
int i = 0;
for(test_array.length)
{
if(test_array[i] == true)
{
count_no_true = i++;
}
}
if(count_no_true == no of function)
{test == 1;}
else
{test == 0;}
}while(test == 1)