XML文件DataGridView高亮空Pos行及多条件筛选问题
解答你的DataGridView高亮与多条件筛选问题
问题1:仅高亮Pos属性值为空字符串的行
你的代码之所以会把整个表格高亮,是因为XML中部分<Log>节点没有Pos属性,DataSet解析后这些行的Pos单元格值是DBNull.Value,当你调用ToString()时,DBNull.Value.ToString()会返回空字符串,导致这些行也被误判为符合条件。
解决方法是先判断单元格值是否为DBNull.Value,再检查是否为空字符串:
for (int i = 0; i < dataGridView1.Rows.Count; i++) { DataGridViewCell posCell = dataGridView1.Rows[i].Cells["Pos"]; string posValue = string.Empty; // 先处理DBNull的情况 if (posCell.Value != DBNull.Value) { posValue = posCell.Value.ToString(); } // 仅当Pos属性存在且值为空字符串时高亮 if (posValue == "") { dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Yellow; } }
如果你想同时包含没有Pos属性(即值为DBNull)和Pos值为空字符串的行,可以简化为:
for (int i = 0; i < dataGridView1.Rows.Count; i++) { string posValue = dataGridView1.Rows[i].Cells["Pos"].Value is DBNull ? string.Empty : dataGridView1.Rows[i].Cells["Pos"].Value.ToString(); if (string.IsNullOrEmpty(posValue)) { dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Yellow; } }
问题2:单个if语句中添加多条件筛选
直接用逻辑运算符&&(逻辑与)和||(逻辑或)组合条件即可,注意用括号明确条件的优先级。比如你需要满足:(Pos为空字符串 或 Pos为"12") 并且 ID为"Opened",代码如下:
for (int i = 0; i < dataGridView1.Rows.Count; i++) { // 获取Pos和ID的单元格值,处理DBNull情况 string posValue = dataGridView1.Rows[i].Cells["Pos"].Value is DBNull ? string.Empty : dataGridView1.Rows[i].Cells["Pos"].Value.ToString(); string idValue = dataGridView1.Rows[i].Cells["ID"].Value is DBNull ? string.Empty : dataGridView1.Rows[i].Cells["ID"].Value.ToString(); // 组合多条件 if ((posValue == "" || posValue == "12") && idValue == "Opened") { dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Yellow; } }
这里的括号很重要,它确保先判断Pos的两个条件,再和ID的条件做“且”运算,避免逻辑混乱。
内容的提问来源于stack exchange,提问作者Baron
相关产品推荐
相关产品推荐

