Reputation: 65
Not sure why setting the ReadOnly property of the row doesn't work (I am still able to edit all the rows) as I am looping through each row in DataGridView:
foreach (DataGridViewRow row in dataGridEthnicityData.Rows)
{
string EthnicityProfilingCompanyName = row.Cells["EthnicityProfilingCompanyName"].Value.ToString();
string EthnicityProfilingCompanyID = row.Cells["EthnicityProfilingCompanyID"].Value.ToString();
if (EthnicityProfilingCompanyName != ProfilingEntityName && EthnicityProfilingCompanyID != ProfilingEntityID)
row.ReadOnly = true;
else row.ReadOnly = false;
}
Appreciate if any one can point me to the right direction. Do I have to change how I loop? I'm thinking to make use of a loop with counter so I can use it as row index.
Thank you.
Upvotes: 0
Views: 1284
Reputation: 125197
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.
Upvotes: 1