DataGridViewComboBoxCell.ReadOnly = true, but can still change the selected value有同样的问题,但用户对我无法实现的答案感到满意。
我有一个包含许多列的dataGridView,其中一列是checkBoxColumn,它应该激活或停用另一个包含文本的列:
现在,一旦加载了dataGridView,我得到的代码就完美了:我点击复选框,它们按预期工作。
问题是我希望dataGridView禁用在加载时间内没有检查相应Allergies单元格的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,并且它们的readonly值正确设置为true ,但它们仍然可以编辑。
答案 0 :(得分:1)
当您从构造函数内部调用DataGridCells时,设置ReadOnly属性似乎很早。试着移动你的电话:
disableNotCheckedAllergiesDescription();
而不是到DataBindingComplete事件。