Click here to Skip to main content
15,904,415 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
How to convert For Each loop into For loop

C#
protected void chkboxmaritalstatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        int count = 0;
        
        foreach (ListItem li in chkboxmaritalstatus.Items)
        {
            if (li.Selected)
                count++;
        }
        if (count > 3)
        {
            rdomaritalstatusprefer.Checked = false;
            rdomaritalstatusprefernot.Checked = true;
            chkboxmaritalstatus.Enabled = false;
            chkboxmaritalstatus.ClearSelection();
        }
    }

i want this for each loop code in to for loop
Posted
Comments
Sergey Alexandrovich Kryukov 11-Feb-14 1:41am    
Why?
—SA

C#
for (int i = 0; i < chkboxmaritalstatus.Items.Count; i++)
           {
               if(chkboxmaritalstatus.Items[i].Selected)
                   count++;
           }
 
Share this answer
 
Comments
Siva Hyderabad 17-Feb-14 1:25am    
5
C#
protected void chkboxmaritalstatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        int index=0;
        for(int i=0;i<chkboxmaritalstatus.items.count;i++){
        if (chkboxmaritalstatus.items[i].Selected)
             index++;
        }
        if(index>3){
          rdomaritalstatusprefer.Checked = false;
          rdomaritalstatusprefernot.Checked = true;
          chkboxmaritalstatus.Enabled = false;
          chkboxmaritalstatus.ClearSelection();
        }
    }
 
Share this answer
 
//hope you are looking for..
C#
protected void chkboxmaritalstatus_SelectedIndexChanged(object sender, EventArgs e)
    {     
        for(int i=0;i<chkboxmaritalstatus.items.count;i++)>
        {
            if (chkboxmaritalstatus.items[i].Selected && i>3)
            {
              rdomaritalstatusprefer.Checked = false;
              rdomaritalstatusprefernot.Checked = true;
              chkboxmaritalstatus.Enabled = false;
              chkboxmaritalstatus.ClearSelection();
            }
            
        }
        
    }

// if your requirement is only the above functionality check this snippet.

C#
if (chkboxmaritalstatus.GetSelectedIndices().Count() > 3)
{
    rdomaritalstatusprefer.Checked = false;
    rdomaritalstatusprefernot.Checked = true;
    chkboxmaritalstatus.Enabled = false;
    chkboxmaritalstatus.ClearSelection();
}
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 11-Feb-14 1:43am    
It's pointless to start this loop from zero. What is that, inertia of thinking?
—SA
s#@!k 11-Feb-14 1:49am    
he just wanted to convert foreach to for loop,it is a sample idea for him.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900