If you want to set the readonly property of the rows in a loop, you should make sure you run the code after the databinding is completed and the rows exist in the DataGridView. A good event for that is DataBindingComplete.
But a better option (instead of a loop over the rows), is handling CellBeginEdit which is a cancelable event and allows you to check a criteria on the cell or the row and decide to allow or deny the edit.
Example - Using CellBeginEdit to conditionally make the Row read-only
class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
var list = new List<Item>() {
new Item(){ Id = 1, Name ="One"},
new Item(){ Id = 2, Name ="Tow"},
};
var dg = new DataGridView();
dg.Dock = DockStyle.Fill;
dg.DataSource = list;
dg.CellBeginEdit += (object obj, DataGridViewCellCancelEventArgs args) =>
{
var row = ((DataGridView)obj).Rows[args.RowIndex];
if ((int)row.Cells[0].Value == 1)
args.Cancel = true;
};
this.Controls.Add(dg);
}
Above code prevents editing of the first row, but allows editing on the second row.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…