Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

c# - How to set the ReadOnly of entire row in DataGridView based on condition?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...