如何为gridview中的特定行执行颜色?

时间:2013-12-29 11:40:14

标签: c# winforms gridview

我正在使用两种形式,当我将StockID从一种形式发送到另一种形式时,在第二种形式中,gridview中有一些数据,现在我想做的就是,通过使用我要突出显示的id那行只。我想比较网格视图中是否存在ID,如果退出,我想要为该完整行做高位。,

if (pc == c)
{
    for (int i = 0; i < grid_stock.Rows.Count; i++)
    {
        grid_stock.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        this.grid_stock.Rows[i].DefaultCellStyle.BackColor = Color.Red;
        break;
    }                       
}

3 个答案:

答案 0 :(得分:0)

试试这个,

StockID

中提供row.Cells[0]的正确列索引
foreach (DataGridViewRow row in grid_stock.Rows) 
{
  if (row.Cells[0].Value.Equals("StockID")) 
  {
    grid_stock.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    row.DefaultCellStyle.BackColor = Color.Red; 
  }
}

答案 1 :(得分:0)

如果顶部的if条件是为了检查ID是否匹配,请将其置于for循环中,如下所示:

for (int i = 0; i < grid_stock.Rows.Count; i++)
{
    if(grid_stock.Rows[i].Cells[stockID_column_index].Value == received_stockID) // Check if the row IDs match here
    {
        grid_stock.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        this.grid_stock.Rows[i].DefaultCellStyle.BackColor = Color.Red;
        break;
    }
}

将stockID_column_index替换为存储StockID的列的索引。

答案 2 :(得分:0)

// on load or when refersh data

if (SelectingID != null)
{
    for (int i = 0; i < dgvInvoiceList.Rows.Count; i++)
    {
        BillingGeneral.InvoicesDataSet.InvoiceListRow dr = (BillingGeneral.InvoicesDataSet.InvoiceListRow)((DataRowView)dgvInvoiceList.Rows[i].DataBoundItem).Row;
        if (dr.ID == SelectingID.Value)
        {
            dgvInvoiceList.ClearSelection();
            dgvInvoiceList.Rows[i].Selected = true;
            SelectingID = null;
            break;
        }
    }
}