foreach (DataGridViewRow dgvr in dataGridViewProductList.Rows)
{
string dgvrID = dgvr.Cells["ID"].Value.ToString();
DataRow[] s = DT.Select("BillID = " + dgvrID);
if (s.Length > 0)
{
dataGridViewProductList.Columns["chk"].ReadOnly = false;
dataGridViewProductList.Rows[dgvr.Index].Cells["chk"].ReadOnly = false;
dataGridViewProductList.Rows[dgvr.Index].Cells["chk"].Value = 1;
}
}运行代码DataGridViewCheckBoxCell后未更改为选中状态,如何更改其选中状态
我试过了
DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)dataGridViewProductList.Rows[dgvr.Index].Cells["chk"];
cell.ReadOnly = false;
cell.TrueValue = true;
cell.Value = cell.TrueValue;但不起作用。
发布于 2016-11-26 16:28:11
一个建议是尝试这样做。在设置true/false值之前,请检查cell.Value是否为null。如果是,则使用cell.Value = true; or cell.Value = false; NOT cell.Value = cell.TrueValue/FalseValue;设置它。下面的代码应该在单击按钮时切换(选中/取消选中)第3列中的每个复选框。如果复选框为空,我将其设置为true。如果我在cell.Value = cell.TrueValue;为空的时候使用它,它就不能工作。
这只是个想法。
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells[2];
if (cell.Value != null)
{
if (cell.Value.Equals(cell.FalseValue))
{
cell.Value = cell.TrueValue;
}
else
{
cell.Value = cell.FalseValue;
}
}
else
{
//cell.Value = cell.TrueValue; // <-- Does not work here when cell.Value is null
cell.Value = true;
}
}
}一个更紧凑的版本,可以切换复选框值--删除了check for false value。
if (cell.Value.Equals(cell.FalseValue))这个if永远不会被输入,因为没有选中的复选框将返回一个空的cell.Value,因此这将被前一个if(cell.Value != null)捕获。换句话说..。如果不为空...已经检查过了。
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)row.Cells[2];
if (cell.Value != null)
{
cell.Value = cell.FalseValue;
}
else
{
//cell.Value = cell.TrueValue; // <-- Does not work here when cell.Value is null
cell.Value = true;
}
}
}希望这能有所帮助。
https://stackoverflow.com/questions/40815711
复制相似问题