检查列中的单元格是否具有相同的值

本文关键字:是否 单元格 检查 | 更新日期: 2023-09-27 18:22:01

我正在制作启动列表,所以很明显,我想防止出现具有相同启动号的竞争对手。我有用于输入值的TextBoxes,通过保存按钮转换为DataGridView表。像这样:

bool CheckFiledIsEmpty()
{
    if (textStN.Text == string.Empty ||
        textN.Text == string.Empty ||
        textSN.Text == string.Empty ||
        textC.Text == string.Empty ||
        textYB.Text == string.Empty)
        return false;
    else
        return true;
}
private void buttonSave_Click(object sender, EventArgs e)
{
    if (CheckFiledIsEmpty())
    {
        string Column1 = textStN.Text;
        string Column2 = textN.Text;
        string Column3 = textSN.Text;
        string Column4 = textC.Text;
        string Column5 = textYB.Text;                    
        string[] row = { Column1, Column2, Column3, Column4, Column5 };
        dataGridView1.Rows.Add(row);
        textStN.Text = "";
        textN.Text = "";
        textSN.Text = "";
        textC.Text = "";
        textYB.Text = "";
    }
    else
    {
        MessageBox.Show("Input all information about competitor!");
    }
}

我希望当点击保存按钮时,会检查Column1(起始号文本框textStN)中以前的值,如果有相同的值,则会出现错误框,如:"具有该起始号的竞争对手已经存在!"

谢谢你的帮助,对不起我的英语。

检查列中的单元格是否具有相同的值

如下修改代码:

bool CompetitorAlreadyExist()
{
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            if (cell.ColumnIndex == 0) // set your column index
            {
                // do your stuff here… i.e., compare `textStN.Text` with all values
                // in column start # and return true or false 
            }
        }
    }
}
private void buttonSave_Click(object sender, EventArgs e)
{
    if (CheckFiledIsEmpty() && CompetitorAlreadyExist())
    {
        string column1 = textStN.Text;
        string column2 = textN.Text;
        string column3 = textSN.Text;
        string column4 = textC.Text;
        string column5 = textYB.Text;                    
        string[] row = { column1, column2, column3, column4, column5 };
        dataGridView1.Rows.Add(row);
        textStN.Text = "";
        textN.Text = "";
        textSN.Text = "";
        textC.Text = "";
        textYB.Text = "";
    }
    else
    {
        MessageBox.Show("Input all information about competitor!");
    }
}

希望它能有所帮助。