【发布时间】:2010-05-21 20:37:11
【问题描述】:
我正在制作一个DataGridView,其中包含一系列复选框,水平和垂直方向具有相同的标签。任何相同的标签,复选框都将处于非活动状态,我只希望每个组合的两个“检查”之一有效。以下屏幕截图显示了我所拥有的:
任何在下半部分被选中的东西,我都希望在上半部分不被选中。因此,如果选中 [quux, spam](或 [7, 8] 用于从零开始的坐标),我希望 [spam, quux] ([8, 7]) 未选中。到目前为止,我有以下内容:
dgvSysGrid.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
dgvSysGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
string[] allsysNames = { "heya", "there", "lots", "of", "names", "foo", "bar", "quux", "spam", "eggs", "bacon" };
// Add a column for each entry, and a row for each entry, and mark the "diagonals" as readonly
for (int i = 0; i < allsysNames.Length; i++)
{
dgvSysGrid.Columns.Add(new DataGridViewCheckBoxColumn(false));
dgvSysGrid.Columns[i].HeaderText = allsysNames[i];
dgvSysGrid.Rows.Add();
dgvSysGrid.Rows[i].HeaderCell.Value = allsysNames[i];
// Mark all of the "diagonals" as unable to change
DataGridViewCell curDiagonal = dgvSysGrid[i, i];
curDiagonal.ReadOnly = true;
curDiagonal.Style.BackColor = Color.Black;
curDiagonal.Style.ForeColor = Color.Black;
}
// Hook up the event handler so that we can change the "corresponding" checkboxes as needed
//dgvSysGrid.CurrentCellDirtyStateChanged += new EventHandler(dgvSysGrid_CurrentCellDirtyStateChanged);
dgvSysGrid.CellValueChanged += new DataGridViewCellEventHandler(dgvSysGrid_CellValueChanged);
}
void dgvSysGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
Point cur = new Point(e.ColumnIndex, e.RowIndex);
// Change the diagonal checkbox to the opposite state
DataGridViewCheckBoxCell curCell = (DataGridViewCheckBoxCell)dgvSysGrid[cur.X, cur.Y];
DataGridViewCheckBoxCell diagCell = (DataGridViewCheckBoxCell)dgvSysGrid[cur.Y, cur.X];
if ((bool)(curCell.Value) == true)
{
diagCell.Value = false;
}
else
{
diagCell.Value = true;
}
}
/// <summary>
/// Change the corresponding checkbox to the opposite state of the current one
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void dgvSysGrid_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
Point cur = dgvSysGrid.CurrentCellAddress;
// Change the diagonal checkbox to the opposite state
DataGridViewCheckBoxCell curCell = (DataGridViewCheckBoxCell)dgvSysGrid[cur.X, cur.Y];
DataGridViewCheckBoxCell diagCell = (DataGridViewCheckBoxCell)dgvSysGrid[cur.Y, cur.X];
if ((bool)(curCell.Value) == true)
{
diagCell.Value = false;
}
else
{
diagCell.Value = true;
}
}
问题来了,如果我使用CellValueChanged 事件,更改的单元格值似乎总是“落后”,您实际单击的位置,如果我在其中,我不确定如何获取当前单元格curCell 的“脏”状态以 null 形式出现(暗示当前单元格地址在某种程度上是错误的,但我没有尝试获取该值)意味着该路径根本不起作用。
基本上,我如何获得具有正确布尔值的“正确”地址,以便我的翻转算法能够工作?
【问题讨论】:
标签: c# .net datagridview checkbox