检查datagridview的第一列是否包含字符串

时间:2017-09-22 06:43:17

标签: c#

大家好日子。

我正在编写一个代码来输入datagridview中的ID号。在添加之前,代码应首先检查数据网格视图中是否已存在“名称”。如果是,则不会将其添加到datagridview并显示消息框。

以下是datagridview项目的外观:

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

以下是我正在处理的代码。字符串s1和s2仍然在datagridview中被复制,即使我已经在“名称”列中有“Thomas”。

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

我可以知道代码中缺少的内容吗?

非常感谢您提供通常的帮助。

2 个答案:

答案 0 :(得分:4)

首先,如果第一列等于' Thomas'那么您正在检查DataGridView中的每一行。这将导致重复记录。

例如,您有:

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

在循环的第一次迭代(Cesar, 10000001)中,您已经为Thomas添加了一个新行!因为column[0]不是null而且它不等于“托马斯”。看到?这是你的第一个错误。

其次,考虑ff。数据:

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

即使在第一次迭代中它是假的,它仍将继续下一次迭代,这将是假的,因此,将添加另一行!

但是,如果你没有托马斯'在DataGridView

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

所有迭代都将通过您的条件,因此您将获得3行,以及#39; Thomas'!

问题是,你是在检查每一行。迭代所有行后应检查您的条件。您需要有一个变量bool found,并在完成迭代后对此进行检查。

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

答案 1 :(得分:0)

非常感谢Geoman。与我的代码工作方式相比,您的代码非常简洁。真的很感激所有的帮助。干杯!!!

            if (dataGridView1 != null)
            {
                foreach (DataGridViewRow item in dataGridView1.Rows)
                {
                    if (item.Cells[0].Value != null && item.Cells[0].Value.ToString() == s1)
                    {
                        label6.Text = "True";                              
                        break;
                    }
                    else
                    {
                        label6.Text = "False";
                    }
                }                        
            }

            if (label6.Text == "False")
            {
                string newline = s1 + "," + s2;
                string[] values = newline.Split(',');
                this.dataGridView1.Rows.Add(values);
            }