如何根据条件设置DataGridView中整行的ReadOnly



不确定为什么设置行的ReadOnly属性不起作用(我仍然可以编辑所有行(,因为我正在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;
}

如果有人能为我指明正确的方向,我将不胜感激。我必须改变循环方式吗?我正在考虑使用一个带计数器的循环,这样我就可以把它用作行索引。

谢谢。

如果要设置循环中行的只读属性,则应确保在数据绑定完成且行存在于DataGridView中后运行代码。DataBindingComplete是一个很好的事件。

但一个更好的选择(而不是在行上循环(是处理CellBeginEdit,这是一个可取消的事件,允许您检查单元格或行上的条件,并决定允许或拒绝编辑。

示例-使用CellBeginEdit有条件地将行设为只读

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);
}

上面的代码禁止编辑第一行,但允许编辑第二行。

最新更新