通过DGVs& amp;中的特定col进行迭代比较字符串值

时间:2012-11-18 07:04:40

标签: c# datagrid datagridview loops

我有2个数据网格视图,第一个数据网格1st col or Index 0&第二个数据网格1st col or Index 0。 我如何遍历datagridviews中的特定col并查找字符串值,如果它与列表匹配则转到函数。

我的方法不起作用。我怎么能这样做?

private void b_calculate_Click(object sender, EventArgs e)
{           
    List<string> value = new List<String>() { "AE0", "AT1", "AT2", "AT3"};
    value = new List<string>(datagridview1.Columns[0].Index);
    List<string> value2 = new List<String>() { "BE0", "BT1", "BT2", "BT3"};
    value2 = new List<string>(datagridview2.Columns[0].Index);

     //First Combination
    if((value.ToString() == "AT1" || value.ToString() == "AE0" || 
         value.ToString() == "AT2")
          && 
         (value2.ToString() == "BT1" || value2.ToString() == "BE0"))
    { 
        gottoFunction1();
    }
    //Second Combination
    if((value.ToString() == "AT1" || value.ToString() == "AT2" )
            && 
           (value2.ToString() == "BT1" || value2.ToString() == "BT2"))
    { 
        gottoFunction2();
    }
}

1 个答案:

答案 0 :(得分:1)

这是一个例程,它迭代DataGridView中的所有可用行,并执行方法中显示的处理:

private void b_calculate_Click(object sender, EventArgs e)
{
    for (var i = 0; i < dataGridView1.RowCount; i++)
    {
        if (dataGridView2.RowCount <= i)
            break;

        var cellFromDG1 = dataGridView1.Rows[i].Cells[0];
        var cellFromDG2 = dataGridView1.Rows[i].Cells[0];

        if (cellFromDG1.Value == null || cellFromDG2.Value == null)
        {
            // this could be the empty row that allows you to
            // enter a new record
            continue;
        }

        var value = cellFromDG1.Value.ToString();
        var value2 = cellFromDG2.Value.ToString();

        if ((value == "AT1" || value == "AE0" || value == "AT2") &&
                (value2 == "BT1" || value2 == "BE0"))
        {
            gottoFunction1();
        }

        if ((value == "AT1" || value == "AT2") &&
            (value2 == "BT1" || value2 == "BT2"))
        {
            gottoFunction2();
        }
    }
}