c# - Why does my if else statement refuses to read a certain row? -


i have table below contains students' results in datagridview:-

id  name    result 1   peter   pass 1   peter   silver 2   sam     fail 2   sam     silver 3   simon   fail 4   cliff   pass 5   jason   fail 5   jason   fail 6   leonard pass 6   leonard fail 

i'm trying produce simple program filter out rows base on results upon click of button. have achieved right have able filter out pass and/or silver result , display out fail.

the problem right whenever button clicked, removed rows pass and/or silver, except 2nd row: 1 peter silver. leaving me table below end result:-

enter image description here

the way resolved right click button again.

below source code button:-

    private void btngenerate_click(object sender, eventargs e)     {        if (dtlist.rows.count != 0)        {            try            {                foreach (datagridviewrow dr in dtlist.rows)                {                    //column names in excel file                    string colid = dr.cells["id"].value.tostring();                    string colname = dr.cells["name"].value.tostring();                    string colresult = dr.cells["result"].value.tostring();                      if (!colresult.equals("fail", stringcomparison.invariantcultureignorecase))                    {                        dtlist.rows.remove(dr);                    }                 }            }            catch            {             }         }      } 

the problem changing list iterating over. never great idea...

in case @ first row (peter/pass) , remove it. @ second row. wait, removed row second row in fact old third row - have skipped original second row.

you don't notice problem anywhere else because other rows want removed followed rows want keep.

the way fix either:

  1. create new list items want keep , bind new list whereever displaying

  2. create list of items want remove datatable while iterating table. once have list of items want remove iterate on list removing them datatable.

  3. iterate through list loop starting last index. mean when remove items effect come after in case have processed.

the second easiest way go in situation. first involves code , third may not obvious why doing comes after you.


Comments