首页 > 解决方案 > 如何突出显示 datagridview 中不等于数据表中的行的行?

问题描述

我有一个 datagridview 包含多行数字。我有一个数据表,其中一列包含数字。

我想突出显示不在数据表行中的 datagridview 行。我只比较一列。

这是我的代码:

DataTable SeatNum = new DataTable();

SeatNum = "Select Nums from dbo.Nums";

try
{
    foreach (DataGridViewRow row in dataGridView2.Rows)
    {
        if (row.IsNewRow) { return; }

        foreach (DataRow dtrow in SeatNum.Rows)
        {
            if (dtrow[0].ToString() != (row.Cells[0].Value.ToString()))
            {
                row.Cells[0].Style.BackColor = Color.Red;
                MessageBox.Show("Not Exist" + row.Cells[0].Value.ToString() + "\r\n" + dtrow[0].ToString(), "Caution", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                break;
            }
            else
            {
                row.Cells[0].Style.BackColor = row.DefaultCellStyle.BackColor;
                MessageBox.Show("Exist" + row.Cells[0].Value.ToString() + "\r\n" + dtrow[0].ToString(), "Caution", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                break;
            }
        }
    }
}
catch (Exception exc)
{
    MessageBox.Show(exc.Message);
}

此代码仅突出显示与数据表中第一行不匹配的行

先感谢您。

标签: c#datagridviewdatatablematchhighlight

解决方案


我修复了代码,现在它像我预期的那样工作。

我更换了:

foreach (DataRow dtrow in SeatNum.Rows)

到 for 循环:

for (int i = 0; i < SeatNum.Rows.Count; i++)

然后我将if语句更改为:

if (SeatNum.Rows[i][0].ToString() != (row.Cells[0].Value.ToString()))

然后我删除了breakinThen语句并将其保留在else语句中。

谢谢。

更新:

更好的解决方案,更快,更合乎逻辑

            DataTable SeatNum;
            List<int> SeatNums = (from row in SeatNum.AsEnumerable() select Convert.ToInt32(row["Num"])).ToList();
            bool OutOfRang = false; ;
            foreach (DataGridViewRow row in dataGridView2.Rows)
            {

                if (!row.IsNewRow)
                {
                    if (!SeatNums.ToList().Contains(Convert.ToInt32(row.Cells[0].Value)))
                    {
                        OutOfRang = true;
                        row.Cells[0].Style.BackColor = Color.Red;
                        MessageBox.Show("This Num ( " + row.Cells[0].Value.ToString() + " ) not in DataTable list");
                        countSeatsbr++;
                        row.ErrorText = "Not in DataTable list.";

                    }
                }
            }
            if (OutOfRang)
            {
                return;
            }
            else
            {
                DoSomethingElse()
            }

推荐阅读