Search code examples
c#datagridviewdatagridviewcolumn

To find the number of rows in DataGridView where the values are between specified range?


One column of my DataGridView contains a number of different values.

For example:

 columnName
    10
    21
    23
    25
    12
    14
    16
    28
    30
    29
    36
    47
    56
    65
    78
    89
    96
    121
    126
    21
    132
    55
    16
    ... etc

Here I need to separate the values which lies between the range 0-30, 30-60, 60-90,[...].

    {
    var sector1 = "no.of values lies between 0-30";
    var sector2 = "no.of values lies between 30-60";
    var sector3 = "no.of values lies between 60-90";
    var sector4 = "no.of values lies between 90-120";
     }

I tried this,

     try
     {
     var values = dataGridView1.Rows.Cast<DataGridViewRow>().Select(x => (int)x.Cells[columnName].Value);
     var sector1 = values.Count(x => x >= 0 && x < 30);
     var sector2 = values.Count(x => x >= 30 && x < 60);
     var sector3 = values.Count(x => x >= 60 && x < 90);
     var sector4 = values.Count(x => x >= 90 && x < 120);
     var sector5 = values.Count(x => x >= 120 && x < 150);
     var sector6 = values.Count(x => x >= 150 && x < 180);
     [...]
     MessageBox.Show(sector1.ToString());
     [...]
     }
     catch
     {
      MessageBox.Show("ERROR");
     }

but no use, i'm getting error notification only.

Can any one suggest the syntax to find the count of rows between two ranges?


Solution

  • Can you please try this code

    var values = gvtest.Rows.Cast<GridViewRow>().Select(x => x.Cells[0].Text);
    var sector1 = values.Count(x => Convert.ToInt32(x) >= 0 && Convert.ToInt32(x) < 30);