简体   繁体   中英

C# Hightlight DataGrid row based if value matches textbox value

How do I highlight a datagrid row based off the value in textbox2?

Ultimately when a matching value is found in Column 2 the QTY field (column 3) on that corresponding row will need change by -1 for each QR Code scanned by the End user. Once the QTY value reaches 0 the the row will need to be highlighted Green.

I can't just get it to work have tried a few different ways of writing the foreach section but no luck

My code is as below:

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

        }
    }

You can do a loop inside all cells of that row and set the cell Style property. You can create different styles for non-selected and selected rows, then apply these styles as necessary.

Example:

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

If you do not want to loop through the cells, you can simply change the DataRow.DefaultCellStyle property of each row. But this will limit your customization options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM