【发布时间】:2020-09-25 11:41:09
【问题描述】:
我有一个从数据表加载的数据网格视图。 我通过 DataGridViewCheckBoxCell 类手动添加三列。 每行将根据用户选中的复选框进行更新。 我面临的问题是如何限制用户从加载的 datagridview 中所选行中的所有三个可用复选框中选择或选中一个复选框。
如果有在 datagridview 列中添加单选按钮的选项,或者我可以添加一组 3 个单选按钮作为每一行的列,问题将得到解决。
This is what my datagrid looks like after adding 3 datagridviewcheckboxCells
我的添加列的代码sn-p是
if (DG.DataSource != null)
{
DataGridViewCheckBoxColumn ChbColReceived = new DataGridViewCheckBoxColumn();
DataGridViewCheckBoxColumn ChbColCancelled = new DataGridViewCheckBoxColumn();
DataGridViewCheckBoxColumn ChbColStop = new DataGridViewCheckBoxColumn();
DG.Columns.Add(ChbColReceived);
DG.Columns.Add(ChbColCancelled);
DG.Columns.Add(ChbColStop);
ChbColReceived.HeaderText = "Received";
ChbColCancelled.HeaderText = "Cancelled";
ChbColStop.HeaderText = "Stopped";
}
您的建议将是可观的。 问候
解决方案: 感谢所有帮助我的开发者/大师。特别感谢@JohnG,他的回答也被勾选了。我已经对其进行了一些更改,这对于回答的人来说可能是可以接受的。这是我的代码解决了我的问题。
private void DG_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
try
{
int colIndex = DG.CurrentCell.ColumnIndex;
int rowIndex = DG.CurrentCell.RowIndex;
bool currentValue;
if (DG.Columns[colIndex].Index == 11 || DG.Columns[colIndex].Index == 12 || DG.Columns[colIndex].Index == 13)
{
DG.CurrentCellDirtyStateChanged -= new EventHandler(DG_CurrentCellDirtyStateChanged);
currentValue = !(bool)DG.Rows[rowIndex].Cells[colIndex].FormattedValue;
switch (DG.Columns[colIndex].Index)
{
case 11:
if (currentValue == true)
{
DG.Rows[rowIndex].Cells[12].Value = false;
DG.Rows[rowIndex].Cells[13].Value = false;
}
break;
case 12:
if (currentValue == true)
{
DG.Rows[rowIndex].Cells[11].Value = false;
DG.Rows[rowIndex].Cells[13].Value = false;
}
break;
case 13:
if (currentValue == true)
{
DG.Rows[rowIndex].Cells[11].Value = false;
DG.Rows[rowIndex].Cells[12].Value = false;
}
break;
}
DG.CommitEdit(DataGridViewDataErrorContexts.Commit);
DG.CurrentCellDirtyStateChanged += new EventHandler(DG_CurrentCellDirtyStateChanged);
}
}
catch (Exception) { throw; }
}
Col[11],Col[12],col[13] 是我的目标复选框列。 感谢@JohnG 的时间和关注。
【问题讨论】:
-
您可以在项目模型中进行设置...基本上在设置器中,如果值为 true,则将其他 bool 值设置为 false ...绑定应该执行此操作(只要实现了
INotifyPropertyChanged) -
你能自己改变数据表类吗?由于它是一个数据表,我假设您也将存储信息?通常我会使用枚举属性(单个字段)并将 3 个复选框列绑定到更新该单个字段的辅助属性。这样可以确保只有一个复选框为真
-
得到不稳定的结果并不奇怪。
CurrentCellDirtyStateChanged中发布的代码检查“EACH”复选框单元格,从 11 开始,然后 12 和 13。这将不起作用。您只想检查“已更改”复选框的值。其他“未更改”复选框无关紧要,因此没有必要选中它们。当您按照您的顺序更改它们时,就会发生这种情况……跟踪代码,您会看到…… -
如果您启动应用程序,第一行的所有复选框都不会被选中。用户单击单元格 13 中的复选框。事件触发... 代码检查单元格 11 的值... 它不正确并被跳过,对于单元格 12 和 13 也是如此。记住,此事件触发“在”复选框更改之前.因此,第一次触发时,所有 if 条件都将返回 false。继续执行会退出事件并将单元格 13 中的复选框设置为 true。
-
现在选中单元格 13,用户单击单元格 11 复选框。事件触发,由于尚未设置 11 中的复选框值,因此检查单元格 11 的第一个 if 语句将为 false。 12 处的单元格也将是错误的。但是,单元格 13 的当前状态为真,并将单元格 11 和 12 设置为假。然后执行离开事件 THEN 单元格 11 设置为真。在这里,您最终会同时检查单元格 11 和 13。
标签: c# datagridview