DataGridViewComboBoxCell.ReadOnly = true,但仍然可以更改所选值有相同的问题,但用户对我无法实现的答案感到满意。
我有一个包含许多列的 dataGridView,其中一个是 checkBoxColumn,它应该激活或停用带有文本的另一列:
现在,一旦加载了 dataGridView,我得到的代码就可以完美运行:我单击复选框,它们按预期工作。
问题是我希望 dataGridView 禁用在加载时没有检查其相应过敏单元格的 AllergiesDescription 单元格。我编写了一个代码,它应该遍历行并在找到未选中的 Allergies 单元格时执行禁用单元格代码。但无论如何,它不起作用!它将所有想要的属性设置为单元格(如 readonly = true),但单元格仍然是可编辑的:
在下面分享我的代码:
private void dataGridView_CellContentClick(object sender,
DataGridViewCellEventArgs cellEvent)
{
if (cellEvent.ColumnIndex == AllergiesCheckBoxColumn.Index)
toggleAllergiesDescriptionHabilitation(cellEvent.RowIndex);
}
private void toggleAllergiesDescriptionHabilitation(int rowIndex)
{
int columnIndex = AllergiesDescriptionTextBoxColumn.Index;
DataGridViewRow row = dataGridView.Rows[rowIndex];
var allergiesDescriptionCell = (DataGridViewTextBoxCell)row.Cells[columnIndex];
var currentCell = (DataGridViewCheckBoxCell)dataGridView.CurrentCell;
if ((bool)currentCell.EditedFormattedValue)
enableCell(allergiesDescriptionCell);
else
disableCell(allergiesDescriptionCell);
}
private void enableCell(DataGridViewTextBoxCell cell)
{
cell.ReadOnly = false;
cell.Style.BackColor = Color.White;
cell.Style.ForeColor = Color.Black;
cell.Style.SelectionBackColor = Color.Blue;
cell.Style.SelectionForeColor = Color.White;
}
private void disableCell(DataGridViewTextBoxCell cell)
{
cell.ReadOnly = true;
cell.Style.BackColor = Color.LightGray;
cell.Style.ForeColor = Color.DarkGray;
cell.Style.SelectionBackColor = Color.LightGray;
cell.Style.SelectionForeColor = Color.DarkGray;
}
正如我所说,该代码完美无缺,每当我检查 Allergies 复选框时,相应的 AllergiesDescription 单元格都会按预期启用或禁用。但:
public People(PersistenceManager persistenceManager)
{
InitializeComponent();
//other stuff
disableNotCheckedAllergiesDescription();
}
private void disableNotCheckedAllergiesDescription()
{
foreach (DataGridViewRow row in dataGridView.Rows)
{
Person person = (Person)row.DataBoundItem;
if (person != null && !person.Allergies)
disableNotCheckedAllergiesDescription(row);
}
}
private void disableNotCheckedAllergiesDescription(DataGridViewRow row)
{
int columnIndex = AllergiesDescriptionTextBoxColumn.Index;
var allergiesDescriptionCell = (DataGridViewTextBoxCell)row.Cells[columnIndex];
disableCell(allergiesDescriptionCell);
}
这不起作用,如您所见,它只为每个应该禁用的单元格执行 disableCell 代码,当我调试时,未选中的行正确进入方法 disableCell,并且它们的只读值正确设置为 true,但是它们仍然可以编辑。