将一行的所有数据网格单元格设置为相同值的最佳方式

本文关键字:设置 单元格 方式 最佳 网格 数据 一行 数据网 | 更新日期: 2023-09-27 18:29:53

我想改进这段代码,它的目标是像excel过滤器一样工作。如果所选行的所有复选框都为true,则函数(由按钮触发)将它们全部设置为false,如果它们全部为false,则将它们设置为true,如果它们中至少有一个为falsetrue,则它们全部变为true。但我的代码只有在它们都是truefalse时才起作用。另一个条件并不总是有效,这是因为代码的最后一部分没有给出正确的结果。复选框位于列3中,从7到19共有21个复选框。

public void seleciona_check()
{
  for (int i = 7; i < grid_lic.ColumnCount-1 ; i++)
  {
    for (int j = 7; j < grid_lic.ColumnCount - 1; j++)
    {
      if (grid_lic.CurrentRow.Cells[j].Value.ToString() == grid_lic.CurrentRow.Cells[i].Value.ToString())
      {
       if (grid_lic.CurrentRow.Cells[i].Value.ToString() == "True")
        {
          Convert.ToBoolean(grid_lic.CurrentRow.Cells[i].Value = false);
          Convert.ToBoolean(grid_lic.CurrentRow.Cells[3].Value = false);
        }
        else if (grid_lic.CurrentRow.Cells[i].Value.ToString() == "False")
        {
          Convert.ToBoolean(grid_lic.CurrentRow.Cells[i].Value = true);
          Convert.ToBoolean(grid_lic.CurrentRow.Cells[3].Value = true);
        }
      }
      else if (grid_lic.CurrentRow.Cells[j].Value.ToString() != grid_lic.CurrentRow.Cells[i].Value.ToString())
      {
        Convert.ToBoolean(grid_lic.CurrentRow.Cells[i].Value = true);
        Convert.ToBoolean(grid_lic.CurrentRow.Cells[j].Value = true);
        Convert.ToBoolean(grid_lic.CurrentRow.Cells[7].Value = true);
        Convert.ToBoolean(grid_lic.CurrentRow.Cells[3].Value = true);
      }
    }
  }
}

将一行的所有数据网格单元格设置为相同值的最佳方式

如果您想处理行,那么您应该遍历行,然后在行的每一列中进行迭代。如果要处理特定行,则必须访问当前行索引并使用它来访问单元格。

您可以从第一列中的值开始,并在迭代时检查它是否发生了更改。如果它发生变化,那么调用一个函数来根据需要设置值,如果没有,则在最后调用该函数。

public void seleciona_check()
    {
        bool changed = false; //boolean to see if something changed 
        bool compareTo=(bool)grid_lic.CurrentRow.Cells[3].Value; // take the first value as reference point
        for (int j = 7; j < grid_lic.ColumnCount - 1; j++) // for loop to check
        {
            if ((bool)grid_lic.CurrentRow.Cells[j].Value != compareTo)
            {
                changed = true; 
                SetAllValues(changed);
                break; //no need to go on if there are true and false values
            }
        }
        if (changed == false) SetAllValues ( compareTo );
    }
    public void SetAllValues(bool toSet)
    {
        for (int j = 7; j < grid_lic.ColumnCount - 1; j++) // for loop to check
        {
            grid_lic.CurrentRow.Cells[j].Value = toSet;
        }
    }