Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I prevent the cells in a DataGrid from being edited without deriving GridColumnStyle?

One solution is to remove all the editing controls from the DataGrid.Controls collection. Without these controls the grid contents cannot be edited. There is a technical problem that requires a little care. You do not want to delete all the controls in DataGrid.Controls as you would lose your scrollbars.

The code below deletes all controls except the scrollbars. Alternatively, you could also loop through the controls and only delete the TextBox.

[C#]

ArrayList list = new ArrayList();
foreach( Control c in dataGrid1.Controls )
  if ( c.GetType() == typeof( VScrollBar ) ||
      c.GetType() == typeof( HScrollBar ) )
    list.Add(c);

dataGrid1.Controls.Clear();
dataGrid1.Controls.AddRange( (Control[]) list.ToArray( typeof( Control ) ) );

[VB.NET]

Dim list As New ArrayList
For Each c As Control In dataGrid1.Controls
  If c.GetType() Is GetType(VScrollBar) Or _
      c.GetType() Is GetType(HScrollBar) Then
    list.Add(c)
  End If
Next

dataGrid1.Controls.Clear()
dataGrid1.Controls.AddRange(CType(list.ToArray(GetType(Control)), Control()))

Contributed from George Shepherd's Windows Forms FAQ



Page view counter