3

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

This is my Datagridview:

enter image description here

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

2
  • 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 in it, using linq. Commented Oct 13, 2015 at 22:54
  • @Marci Let me know if you have any question about the answer or if you find it helpful, you can kindly click the check mark near the answer to make it accepted. This way it will be more useful for other users too. Commented Oct 14, 2015 at 18:59

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget to add using System.Linq;
0

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.