How to make an excel ReadOnly cell using C #?

Range range= (Range)this.workSheet.Cells[1,1]; range.AllowEdit = false; 

When I set the AllowEdit property to false, a compilation error will show:

Error: The property or index "Microsoft.Office.Interop.Excel.Range.AllowEdit" could not be assigned - read-only

How to set a range of read-only cells?

When I use validation for this range, I got some exception from my CellContentChanged event.

Here is the code that is in CellContentChanged:

  var updater = new Action<StyleColorItem>( item => { var editedItem = _taskViewModel.TrackedItems.First(it => it.Id == item.Id); // Above line I am getting the exception like "Sequence contains no matching element" editedItem.Update(item);' }); 
+6
source share
2 answers

It is not possible to make a read-only cell in excel.

What you can do in your C # code, define a cell that will be read-only in a variable or list, subscribe to the SheetChange event in the SheetChange event, if that cell changes, just discard that change.

Private List example readOnlyCells = new List ();

 private void OnActiveSheetCellChange(object changedSheet, Excel.Range changedCell) { if (readOnlyCells.Contains(changedCell)) changedCell.Value = string.Empty; //.... YOUR CODE 

Update

Another alternative is to use data validation:

 changedCell.Validation.Add(Excel.XlDVType.xlValidateCustom, Type.Missing, Type.Missing, "\"\""); 

Using it, you will have less control, and the cell simply will not accept any input.

+3
source

I think this can be done by setting the Locked property to true and protecting the worksheet.

 range.Locked = true; this.workSheet.Protect(Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 
+1
source

Source: https://habr.com/ru/post/915660/


All Articles