How to count specific values in a column of datagridview column

北慕城南 提交于 2019-12-31 04:37:10

问题


In a DataGridView I need to count how many duplicate values a column has.

This is my Datagridview:

For example, I'd like to count how many "X" I have in my "RisFin" column, and put the result in a textbox.


回答1:


You can count what you need this way:

var count= this.dataGridView1.Rows.Cast<DataGridViewRow>()
               .Count(row => row.Cells["RisFin"].Value == "X");

this.textBox1.Text = count.ToString();

Using linq queries you can simply do many things with your grid. and the key point is casting the Rows collection to an IEnumerable<DataGridViewRow> using Cast<DataGridViewRow>(), then you can perform any query on it, using linq.




回答2:


Well, you could just iterate through the rows and increment your counting variable if row.Cells[0] is "X". Here's a LINQ solution.

int xCount = dataGridView.Rows
                .Cast<DataGridViewRow>()
                .Select(row => row.Cells["RisFin"].Value.ToString())
                .Count(s => s == "X");


来源:https://stackoverflow.com/questions/33113755/how-to-count-specific-values-in-a-column-of-datagridview-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!