Thomas Arriola Thomas Arriola -3 years ago 251
C# Question

Checking if first column of datagridview contains a string

Good day to all.

I am writing a code to input ID numbers in a datagridview. Before adding it, the code should check first if the "Name" is already present in the datagridview. If it is, then it will not add it to the datagridview and will display a messagebox.

Below is how the datagridview items looks like:

Name | ID Number
Thomas | 10000000
Cesar | 10000001
Kathrina | 10000002


Below is the code I am working on. String s1 and s2 is still being copied in the datagridview even I already have "Thomas" in the "Name" column.

string s1 = "Thomas";
string s2 = "10000003";

if (dataGridView1 != null)
{
foreach (DataGridViewRow item in dataGridView1.Rows)
{
if (item.Cells[0].Value != null && item.Cells[0].Value.ToString() != s1)
{
string newline = s1 + "," + s2;
string[] values = newline.Split(',');

this.dataGridView1.Rows.Add(values);
}
else
{
MessageBox.Show("Name already exists in the database");
}
}
}


Can I know what I am missing in my code?

Thank you very much in advanced for the usual help.

Answer Source

First, you are checking for each row in your DataGridView if the first column is equal to 'Thomas' which would result to duplicate records.

For example, you have:

Name     | ID Number
---------+----------
Cesar    | 10000001
Thomas   | 10000000
Kathrina | 10000002

In the first iteration of your loop (Cesar, 10000001), you will already add a new row for Thomas! Because column[0] is not null and it doesn't equal to 'Thomas'. See? Here's your first wrong.

Second, consider ff. data:

Name     | ID Number
---------+----------
Thomas   | 10000000
Cesar    | 10000001
Kathrina | 10000002

Even if in your first iteration it is false, it will still continue to the next iteration which would be false, and thus, will add another row!

But what if you don't have 'Thomas' in your DataGridView?

Name     | ID Number
---------+----------
Cesar    | 10000001
Tymothy  | 10000000
Kathrina | 10000002

All iterations will pass in your condition and so you will get 3 rows for 'Thomas'!

The problem is, you are checking per row. Your condition should be checked after iterating all rows. You need to have a variable bool found and this will be checked against after completing the iteration.

string s1 = "Thomas";
string s2 = "10000003";
bool found = false;

if (dataGridView1 != null) {
  foreach(DataGridViewRow item in dataGridView1.Rows) {
    if (item.Cells[0].Value != null && item.Cells[0].Value.ToString() == s1) {
      found = true;
      break; //stop iteration here since it's already found
    }
  }
  if (!found) {
    string newline = s1 + "," + s2;
    string[] values = newline.Split(',');
    this.dataGridView1.Rows.Add(values);
  } 
  else
    MessageBox.Show("Name already exists in the database");
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download