【发布时间】:2014-04-23 16:26:09
【问题描述】:
IDE:Visual Studio c#、Winforms 应用程序。
我已经投入了大约 12 个小时,但没有获得成功。由于DataGridView 不提供单选按钮类型的单元格。所以我正在尝试使用复选框单元格作为单选按钮功能。
即我只想在一列中选中一个复选框。
看图:
这看起来很简单,但相信我,它并不像我们想象的那么简单。回复前请测试代码。
这是我尝试过的示例测试代码:
代码 1
////start
if (e.RowIndex != -1)
{
if (dataGridView1.Rows[e.RowIndex].Cells[0].Value != null && dataGridView1.CurrentCell.ColumnIndex == 0) //null check
{
if (e.ColumnIndex == 0)
{
if (((bool)dataGridView1.Rows[e.RowIndex].Cells[0].Value == true))
{
for (int k = 0; k <= 4; k++)
{
//uncheck all other checkboxes but keep the current as checked
if (k == dataGridView1.CurrentRow.Index)
{
dataGridView1.Rows[k].Cells[0].Value = false;
}
//if (gvTeam1.Rows[k].Cells[2].Selected != null)
//if(k !=e.RowIndex)
}
// gvTeam1.Rows[e.RowIndex].Cells[2].Value = false; // keep the current captain box checked
}
}
//}
// gvTeam1.Rows[rowPointerTeam1].Cells[2].Value = true;
}
}
//end
// here gvTeam1 is Datagridview1
代码 2: 在datagridview1上测试
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 0)
{
for (int i = 0; i < 8; i++)
{
//if (i != dataGridView1.CurrentCell.RowIndex)
dataGridView1.Rows[i].Cells[0].Value = false;
}
dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value = true;
}
}
【问题讨论】:
-
我原来在这里回答过:stackoverflow.com/questions/10438613/…
标签: c# winforms checkbox datagridview