Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k 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

1 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...