【问题标题】:How can the datagridview directly after assign a value in code?在代码中赋值后如何直接datagridview?
【发布时间】:2019-08-12 09:26:40
【问题描述】:

我有一个 WinForms 应用程序,我在表单中使用 datagridview。 DataGridView 有许多复选框列,可以通过代码选择和处理单元格。

因此可以选中/取消选中所有单元格或从剪贴板复制/插入。除了最后一个选中的复选框外,这工作正常。只要单元格被选中,第一个值就不会显示。

我尝试设置SuspendLayoutRefreshUpdate,然后设置ResumeLayout。但是其中任何一个都不适合我。

private void SetCheckBoxCells(bool value)
{
  myDataGridView.SuspendLayout();

  foreach (var cell in myDataGridView.SelectedCells)
  {
    (cell as DataGridViewCheckBoxCell).Value = value;
  }

  myDataGridView.Refresh();
  myDataGridView.Update();         
  myDataGridView.ResumeLayout();
}

我希望在单击菜单条目后所有单元格都在视觉上设置/取消设置,但在取消选择单元格后最后一个在视觉上设置。

【问题讨论】:

    标签: c# winforms datagridview datagridviewcheckboxcell


    【解决方案1】:

    这个问题几乎肯定不是由Refresh/Update 引起的。如果这是一个问题,您会在其他单元格中第一次手动编辑后看到正确的值。您也可以检查值,即:

    MSgbox(myDataGridView.Rows[1].Cells[0].Value.ToString);
    

    显然,索引正确。不过,我相信你会得到你所看到的。

    SelectedCells 中的foreach 应该非常健壮并且不会出现索引错误,所以我会仔细检查CellEdit 状态、CurrentCell 焦点或某些事件是否不会干扰第一个单元格,阻止它被更新。

    也许尝试将当前单元格设置为所选范围之外的内容:

    myDataGridView.CurrentCell = myDataGridView.Rows[1].Cells[0];
        // some other cell not included in selection
    

    整数(x1 到 y2)在那里做什么?他们没有工作。刚结束测试?尝试直接解决麻烦的单元格(仅用于调试),就像这样:

    myDataGridView.Rows[1].Cells[0].value = True
    

    显然有正确的索引。也许它会更多地说明问题。

    【讨论】:

    • 坦克很多!我的问题中的 x1 到 y2 整数在这里不需要,所以我删除了它们。这样就可以了(选择一个单元格外部SelectedCells)。之后,我再次将CurrentCell 设置在之前的第一个单元格中。 myDataGridView.CurrentCell = myDataGridView.Rows[0].Cells[myDataGridView.ColumnCount - 1]; myDataGridView.CurrentCell = myDataGridView.Rows[y2].Cells[x2];
    猜你喜欢
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    相关资源
    最近更新 更多