c# - 如何突出显示 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);
}
此代码仅突出显示与数据表中第一行不匹配的行
先感谢您。
解决方案
我修复了代码,现在它像我预期的那样工作。
我更换了:
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()))
然后我删除了break
inThen
语句并将其保留在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()
}
推荐阅读
- c# - 想玩 Handheld.Playfullscreenmovie 延迟后
- java - 如何生成 30 个随机分数并将它们打印在不同的行上?
- algorithm - 如何解决数组之间的最高组合总数?
- reactjs - 根据日期创建部分
- javascript - 带有方法的 Javascript 对象
- python - 添加链接以返回类别时出现 NoReverseMatch 错误
- c++ - gRPC 的异步使用
- redux - 我的 reducer 的 switch 语句的一部分以意想不到的方式工作,请查看代码
- google-cloud-platform - 我无法在 GCP 中创建组
- javascript - 为什么类方法中的这个值不等于对象本身?