for循环中的多个if条件
本文关键字:if 条件 循环 for | 更新日期: 2023-09-27 18:01:40
我的应用程序在datagridview中搜索特定字符串的所有单元格,并将相邻单元格中的相应值求和为十进制变量。在下面的代码中,当我用Anotherstring条件取出嵌套的if时,我的代码运行完美。当我将嵌套的if条件插入到代码中时,它不会运行。我做错了什么?
decimal amount = 0;
decimal sum = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int index = 0; index < dataGridView1.ColumnCount - 1; index++)
{
DataGridViewCell cell = row.Cells[index];
if (cell.Value == DBNull.Value || cell.Value == null)
continue;
if (cell.Value.ToString().Contains("String"))
{
if (cell.Value.ToString().Contains("Anotherstring"))
{
DataGridViewCell next = row.Cells[index + 1];
string s4 = next.Value.ToString();
amount += Decimal.Parse(s4, NumberStyles.Currency, custom);
textBox50.Text = amount.ToString();
}
DataGridViewCell nexter = row.Cells[index + 1];
string s5 = nexter.Value.ToString();
sum += Decimal.Parse(s5, NumberStyles.Currency, custom);
textBox41.Text = sum.ToString();
}
您可能会进入内部if语句,但Contains是区分大小写的。所以你要么想用小写,要么如果你关心大小写,在你的检查中使用正确的大小写。
if (cell.Value.ToString().ToLower().Contains("string"))
{
if (cell.Value.ToString().ToLower().Contains("anotherstring"))
{
DataGridViewCell next = row.Cells[index + 1];
string s4 = next.Value.ToString();
amount += Decimal.Parse(s4, NumberStyles.Currency, custom);
textBox50.Text = amount.ToString();
}
DataGridViewCell nexter = row.Cells[index + 1];
string s5 = nexter.Value.ToString();
sum += Decimal.Parse(s5, NumberStyles.Currency, custom);
textBox41.Text = sum.ToString();
}
Contains方法区分大小写。在您的示例中,"Anotherstring"不包含"String",因此嵌套的if语句将不匹配。
如果需要不区分大小写的匹配,可以考虑使用IndexOf()