C# Foreach statement not working on datagrid

Discussion in 'C#' started by markyjj, Jun 11, 2013.

  1. markyjj

    markyjj New Member

    Joined:
    Dec 7, 2005
    Messages:
    19
    Likes Received:
    0
    Trophy Points:
    0
    I need help on a program I am currently creating as I am trying to use a foreach statement on a DataGridView & loop through the rows & cells. I have tried the dataview but this doesn’t seem to have the properties to count through cells. I have therefore tried to use a for each statement on a datagridview to loop through the rows, then the cells & count the cells. However, when I run the code & press the button to execute the loop, the code just bypasses the foreach statement & does not count the rows. I have looked through lots of examples but can’t seem to get this working and its really frustrating. Below is the code with the loop. I need help please
    Code:
    
    Dv = new DataView(Movset1.Tables[0]);
                DataGridView Dgv1 = new DataGridView();
                Dgv1.DataSource = this.Dv.Table;
                     
                int CellCount = 0;
                foreach (DataGridViewRow dr in Dgv1.Rows)
                {
                   foreach (DataGridViewCell dc in dr.Cells)
                    {
                        Rowcount++;
                 }
                }
                MessageBox.Show(" there are " + CellCount + " Cells ");
    
    
    
     
  2. Ami Desai

    Ami Desai Member

    Joined:
    Jan 5, 2017
    Messages:
    42
    Likes Received:
    17
    Trophy Points:
    8
    Location:
    Ahmedabad
    Home Page:
    http://www.ifourtechnolab.com/
    Hi,

    You can loop through DataGridView using Rows property as below

    Code:
    foreach (DataGridViewRow r in datagridviews.Rows)
    {
       currQty += r.Cells["qty"].Value;
       // other code
    }
    Thanks
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice