【问题标题】:Iterate through specific col in DGVs' & compare the string values遍历 DGV 中的特定 col 并比较字符串值
【发布时间】:2012-11-18 07:04:39
【问题描述】:

我有 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();
    }
}

【问题讨论】:

    标签: c# datagrid datagridview loops


    【解决方案1】:

    这是一个例程,它遍历DataGridViews 中的所有可用行并执行您的方法中显示的处理:

    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();
            }
        }
    }
    

    【讨论】:

    • 当我测试gottoFunction1();的函数时,第二个函数也执行gottoFunction2();,正常吗??
    • @linguini 在某些情况下,是的。例如,当value == "AT1"value2 == "BT1"
    • @linguini 如果还不行,请查看您的if 条件
    猜你喜欢
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    相关资源
    最近更新 更多