C# 选中 DatagridView 复选框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/673361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:50:43  来源:igfitidea点击:

DatagridView Checkbox Checked?

c#windows

提问by

i have a check box in a datagridview windows form and have a event handler cell_Click on cell click i check the datagridview column for a check box it shows true if the cell is selected too(that is the check box is unchecked and only the the datagrid view cell is selected) and the check box is not selected .i tried for the column gettype and found out the type it shows DatagridViewCheckBox but wrong checked values .???

我在 datagridview windows 窗体中有一个复选框,并且在单击单元格时有一个事件处理程序 cell_Click 我检查了 datagridview 列中的复选框,如果该单元格也被选中,它显示为真(即复选框未选中,只有数据网格视图单元格被选中)并且复选框未被选中。我尝试了列 gettype 并发现它显示的类型 DatagridViewCheckBox 但错误的选中值 .???

回答by Clyde

Several things here:

这里有几件事:

  • the cell click event just means that the user clicked with the mouse button on the data grid view, what you're looking for is probably the CellValueChanged
  • this event will give you the coordinates of the cell that changed. You should check to see if it's in your check box column, then get a reference to the cell and you can check the cell.Value to see if it's true or false. You're not going to find any values on the DataGridViewCheckBoxColumn -- it's going to be at the cell level, and you'll always find the value stored in cell.Value, no matter what type of column it is.
  • 单元格单击事件仅表示用户在数据网格视图上单击鼠标按钮,您要查找的可能是 CellValueChanged
  • 此事件将为您提供更改的单元格的坐标。您应该检查它是否在您的复选框列中,然后获取对该单元格的引用,然后您可以检查 cell.Value 以查看它是真还是假。您不会在 DataGridViewCheckBoxColumn 上找到任何值——它将位于单元格级别,并且您将始终找到存储在 cell.Value 中的值,无论它是什么类型的列。

回答by Ian

If I understand you correctly you are saying the checkbox value does not align with the underlying data?

如果我理解正确,您是说复选框值与基础数据不一致?

This may well be because the data has been updated and is 'dirty', e.g. it hasn't been committed to the datasource yet. If you add an event handler like this:

这很可能是因为数据已经更新并且是“脏的”,例如它还没有提交到数据源。如果您添加这样的事件处理程序:

private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
   if (dataGridView1.CurrentCell is System.Windows.Forms.DataGridViewCheckBoxCell)
   {
      dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
   }
}

Then that should update the datasource and you'll have the correct checkbox state when you query the cell.

然后应该更新数据源,当您查询单元格时,您将拥有正确的复选框状态。