Cristian M
Cristian M

Reputation: 725

How to make WPF datagrid cell ReadOnly for certain rows?

I use a WPF data grid to edit a database table. The table contains several records with 16 columns (properties).

I want to make a column read only if the user tries to edit it when one of the columns of the selected record has a specific value (in other words, disable editing of that particular column for certain records).

I was thinking to bind to column IsReadOnly property, but I do not know how to pass the column which I need to verify (or at least the current row) as a converter parameter.

Does anybody have an idea how to do this?

Upvotes: 1

Views: 5035

Answers (2)

Cristian M
Cristian M

Reputation: 725

I found a solution here. Using the DataGrid.BeginningEdit event to conditionally check if the cell is editable and then set the Cancel property on the event args if not.

Conditionally making readonly to WPF DataGridCell

I don't know if it's the best solution, but it works.

Upvotes: 3

rmojab63
rmojab63

Reputation: 3631

I suggest making the specific DataColumn Readonly, while setting the ItemsSource of the DataGrid. Consider the following as an example:

        DataTable tab = new DataTable();
        DataColumn col = tab.Columns.Add("a");
        // data added code
        foreach (DataColumn col in tab.Columns)
        foreach (DataRow r in tab.Rows)
        {
                if (r[col].Equals("..."))
                {
                    col.ReadOnly = true;
                    break;
                }
        }

Upvotes: 0

Related Questions