如果Grid具有特定价值&在表单加载时突出显示它

时间:2012-03-20 08:25:41

标签: c# winforms visual-studio datagridview

我有一个字符串& datagridview的。在表单加载时,如果网格在第1列(在任何行中)具有该字符串,我希望该网格突出显示特定单元格。

我尝试使用dataGridView1.SelectedRows[1].Cells[1].Selected = true;(硬编码)来检查它是否突出显示。

但它说“指数超出范围”

更新

我有的字符串是MANAGER4&如果Grid在其列中具有值MANAGER4&我想将其显示为selctedcell

enter image description here

4 个答案:

答案 0 :(得分:2)

考虑到您正在讨论 first 列,为什么要使用索引1访问单元格?

使用0访问它。

如果没有选择任何行,您也可以使用SelectedRows集合。

要使用DataGrid单元格着色,您需要使用Cell Styles

编辑

你可以在某些功能中使用这样的东西:

for (int x = 0; x < grid.Rows.Count; x++)
{

  if (..condition..)
  {
    //Red color set on the cell
    grid.Rows[x].Cells[0].Style.BackColor = System.Drawing.Color.Red;

  }
}

答案 1 :(得分:1)

它对我有用。

  for (int x = 0; x < dataGridView1.Rows.Count; x++)
   {
        if (dataGridView1.Rows[x].Cells[0].Value.ToString() == yourString)
        {
             dataGridView1.Rows[x].Cells[0].Selected = true;

        }

    }

答案 2 :(得分:0)

您正在寻找的内容可以通过处理网格的CellFormatting事件来完成。

在其中只需检查特定单元格(对应于您的列),然后您可以根据需要设置背景颜色。这将显示红色单元格(我假设是你想要的)

void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
       //check condition and assign color
       e.CellStyle.BackColor = Color.Red;                    
    }
 }

答案 3 :(得分:0)

首先,您应该将FullRowSelect的{​​{1}}属性设置为DataGridView,以便能够选择单个单元格。之后,您可以轻松选择所需的单元格:false,其中datagridView1.Rows[rowInd].Cells[colInd].Selected = truerowInd分别是行和列的索引(您应该记住,索引从0开始) )。

您遇到colInd例外,因为您尚未选择任何行时尝试访问IndexOutOfRange的{​​{1}}集合。