【问题标题】:C# Change DataGrid Cell Value based on matching text box stringC#根据匹配的文本框字符串更改DataGrid单元格值
【发布时间】:2017-05-08 08:50:06
【问题描述】:

我有一个包含三列的数据网格:

套件编号部件编号数量

我正在编写一个条形码扫描器 winform 应用程序,当部件号被扫描到文本框时,如果它与 DataGrid 中的部件号匹配,Qty 将减少 1。一旦Qty 达到 0行将突出显示绿色,并且不再允许减少 Qty

这样做的最佳方法是什么?我的第一个想法是搜索 DataGrid 的循环。有什么更高效的吗?

【问题讨论】:

    标签: c# winforms loops datagrid


    【解决方案1】:

    你试过foreach循环吗?

    foreach (DataGridViewRow item in this.dataGridView1.Rows)
    {
       if (item.Cells[1].Value.ToString() == txtPart.Text)
        {
           item.ReadOnly = false;         
           this.dataGridView1.CurrentCell = convert it to int and minus -1;
        }
    }
    

    如果数量值为零,则与将其涂成绿色的方法相同。

    【讨论】:

      【解决方案2】:

      ①获得零件编号输入后,使用 LINQ 定位具有特定零件编号的项目。 ②查看数量值。如果 !>0,将行的 bg 变成绿色或其他。

      YourItemSourceType temp = YourDataGridItmesSource.Where(ThatItemYouWant => ThaItemYouWant.PartNumber == InputPartNumber).FirstOrDefault();
      //①:Get the item with specific Part Number.
      //use'?.' in case there is no match for InputPartNumber.
      if(temp?.Qty !< 0)
      {
          temp.Qty --;
          NotifyTheChange();
          //update your view  if you need to update it manually
      }
      else
          CalculateTheItemPositionAndPaintItGreen();
          //②
      

      【讨论】:

      • 有非 LINQ 选项吗?我宁愿不使用它,因为我对 C# 相当陌生
      • 许多有用的工具都是为了简化问题而发明的,LINQ 也是如此,因为它可以以优雅的方式处理简单和复杂的情况(更容易阅读,错误更少)。
      • 所以这发生在我找到零件号的 KeyDown 事件中? String searchValue = textBox2.Text; int rowIndex = -1; foreach (DataGridViewRow row in iCBOMHDataGridView.Rows) { if (row.Cells["0"].Value.ToString().Equals(searchValue)) { &lt;temp messgae box here&gt; } else { &lt;temp messgae box here&gt; } }
      猜你喜欢
      • 2012-05-05
      • 1970-01-01
      • 2011-07-29
      • 2020-08-24
      • 2021-08-09
      • 2010-09-27
      • 1970-01-01
      相关资源
      最近更新 更多