【问题标题】:C# Hightlight DataGrid row based if value matches textbox value如果值与文本框值匹配,则基于 C# 突出显示 DataGrid 行
【发布时间】:2017-05-03 13:03:42
【问题描述】:

如何根据 textbox2 中的值突出显示数据网格行?

最终,当在第 2 列中找到匹配值时,相应行上的 QTY 字段(第 3 列)需要为最终用户扫描的每个 QR 码更改 -1。一旦 QTY 值达到 0,该行将需要突出显示为绿色。

我不能让它工作已经尝试了几种不同的方式来编写 foreach 部分,但没有运气

我的代码如下:

private void textBox2_KeyPress(object sender, KeyEventArgs e)
  {
      if (e.KeyCode == Keys.Enter)
      {
         iCBOMHDataGridView.DataSource = iCBOMHBindingSource;

            string input = textBox2.Text;
            string output = "";
            textBox2.Text = Regex.Replace(input, @"^\d{4}|[A-z]{2}[0-9]{5},|,|,|\d{|[0-9]{4}/....|\d{1,}\/\d{2,2}\/\d{4}|\s.........|\s|,|,|,|\d*?.$|[*?:/]\n|\r|\r\n", output);

               foreach (DataGridViewRow row in iCBOMHDataGridView.Rows)
               {
                if ((string)row.Cells[2].Value == textBox2.Text)
                    {
                        row.Selected = true;
                    }
                else
                    {
                        row.Selected = false;
                        MessageBox.Show("Part Number doesn't match");
                    }
               }

        }
    }

【问题讨论】:

    标签: c# winforms datagrid


    【解决方案1】:

    您可以在该行的所有单元格中执行循环并设置单元格的 Style 属性。您可以为未选中和选中的行创建不同的样式,然后根据需要应用这些样式。

    例子:

    DataGridViewCellStyle selectedStyle = new DataGridViewCellStyle();
    selectedStyle.BackColor = Color.LemonChiffon;
    selectedStyle.ForeColor = Color.OrangeRed;
    
    DataGridViewCellStyle defaultStyle = new DataGridViewCellStyle();
    defaultStyle.BackColor = System.Drawing.Color.White;
    defaultStyle.ForeColor = Control.DefaultForeColor;
    
    foreach (DataGridViewRow row in iCBOMHDataGridView.Rows)
    {
        if ((string)row.Cells[2].Value == textBox2.Text)
        {
            row.Selected = true;
    
            if(Decimal.Parse(row.Cells[3].Value.ToString()) > 0)
                row.Cells[2].Value = Decimal.Parse(row.Cells[2].Value.ToString()) - 1;
        }
    
        if (Decimal.Parse(row.Cells[3].Value.ToString()) <= 0)
        {
            foreach (DataGridViewCell col in row.Cells.AsParallel())
                col.Style = selectedStyle;
        }
        else
        {
            foreach (DataGridViewCell col in row.Cells.AsParallel())
                col.Style = defaultStyle;
        }  
    }
    

    如果您不想循环遍历单元格,您可以简单地更改每一行的 DataRow.DefaultCellStyle 属性。但这会限制您的自定义选项。

    【讨论】:

    • 最终当找到匹配值时,相应行上的 QTY 字段将需要为最终用户扫描的每个 QR 码更改 -1。一旦 QTY 值达到 0,该行将需要突出显示为绿色。
    • 然后仅在条件检查 QTY 列是否为零后应用样式。 if ((string)row.Cells[cQTY.Name].Value
    猜你喜欢
    • 2020-08-12
    • 1970-01-01
    • 2017-10-11
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多