Michael Lewis
Michael Lewis

Reputation: 147

Only allow 2 duplicate values in a datagridview at a time C#?

How can I limit duplicates in a datagridview to two?

I check with this code:

// Start check for number of positions being inserted into datagrid 2

        foreach (DataGridViewRow row in optimaldataGridView.Rows)
        {
            if (row.Cells[3].Value.ToString().Contains("PG"))
               MessageBox.Show ("PG has been selected");

        }

However I need to have something like:

if (row.Cells[3].Value.ToString().Contains("PG")) AND Count > 2 THEN 
    MessageBox.Show ("You have reached your max");

Upvotes: 0

Views: 53

Answers (2)

Michael Lewis
Michael Lewis

Reputation: 147

Thank You, Thhat was it Earvin, I was able to get it to work with the following:

  //Start check for number of positions being insterted into datagrid 2
        int count = 0;
        foreach (DataGridViewRow row in optimaldataGridView.Rows)
        {
            if (row.Cells[3].Value.ToString().Contains("PG"))
            count += 1;
            if (count > 2)
                {

                MessageBox.Show("You have exceeded your max");

            }
        }

Upvotes: 1

Earvin Nill Castillo
Earvin Nill Castillo

Reputation: 70

Create a variable count and add 1 whenever there is a PG on your datagrid

 foreach (DataGridViewRow row in optimaldataGridView.Rows)
    {
        if (row.Cells[3].Value.ToString().Contains("PG"))
           MessageBox.Show ("PG has been selected");
           count+=1;
    }

if count>=2{

msgbox("You have reached your max");

}

Upvotes: 0

Related Questions