Click here to Skip to main content
15,910,787 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more: , +
C#
foreach (DataGridViewRow Row in DGViewTWInv.Rows)
                {
                    if (Row.Cells[0].Value != CardId)
                    {
                       Code Here
                    }
                }


I need to check if a value say a Roll Number is already present in the datagridview than no action required but if the Roll NUMBER doesn't match than I need to insert a new row in the datagridview with the other details along with that Roll Number Found.
But the issue coming is with the first row insertion as the foreach allows only to get in its loop if their is atleast one row in that datagridview.
Currently i have done it by allowing user to add rows which makes by default a null row in the datagridview which makes it possible for first loop entering.
Now I don't want it now and want to remove that null default row.How it can be done?
Posted
Updated 23-Dec-13 7:42am
v2
Comments
Sergey Alexandrovich Kryukov 18-Dec-13 13:33pm    
You code looks fine for the purpose (the whole idea to make such a blind-folded search in a control is pretty bad), but your explanation is not clear at all, the problem is not explained.
—SA

1 solution

The concept of your loop is wrong ... you will end up adding a row each time you encounter one where the CardId is not matched. If CardId is 2 and you have a grid with 0,1,2 then you will add a row when you encounter 0, then again when you encounter 1.

If the datagridview is empty (as you say) you won't enter the code within the foreach loop - but this tells you that the CardId definitely isn't in the data! So do the adding of the row outside of that loop. Here's one way of doing that ...
C#
//Make sure that AllowUserToAddRows = false;
int rowFound = -1;  // As -1 cannot refer to a row in the DGV this will indicate "not found"
foreach (DataGridViewRow row in DGViewTWInv.Rows)
{
    if (int.Parse(row.Cells[0].Value.ToString()) == CardId)
    {
        rowFound = row.Index;   // If we find the data then note where we found it
        break;                  // You can opt to break out of the loop if you don't mind hidden "goto"
    }
}
// Now check to see if we already have that ID and if not add it in
if (rowFound == -1)
    this.DGViewTWInv.Rows.Add(CardId, "Other Data");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900