2009-01-28 Ivan N. Zlatev <contact@i-nz.net>
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / DataGridView.cs
index e5baa1b5a9883ea6400b3d78443699950798a900..462552804f86cbab147c53d7a1a976c660eb9e20 100644 (file)
@@ -21,6 +21,7 @@
 //
 // Author:
 //     Pedro Martínez Juliá <pedromj@gmail.com>
+//     Ivan N. Zlatev <contact@i-nz.net>
 //
 
 #if NET_2_0
@@ -117,7 +118,9 @@ namespace System.Windows.Forms {
                private HScrollBar horizontalScrollBar;
                private VScrollBar verticalScrollBar;
                private Control editingControl;
-               private bool new_row_commited = true;
+               private bool is_autogenerating_columns = false;
+               private bool is_binding = false;
+               private bool new_row_editing = false;
                
                // These are used to implement selection behaviour with SHIFT pressed.
                private int selected_row = -1;
@@ -187,6 +190,7 @@ namespace System.Windows.Forms {
                        columnHeadersVisible = true;
                        columns = CreateColumnsInstance();
                        columns.CollectionChanged += OnColumnCollectionChanged;
+                       currentCellAddress = new Point (-1, -1);
                        dataMember = String.Empty;
                        defaultCellStyle = new DataGridViewCellStyle();
                        defaultCellStyle.BackColor = SystemColors.Window;
@@ -262,7 +266,11 @@ namespace System.Windows.Forms {
 
                [DefaultValue (true)]
                public bool AllowUserToAddRows {
-                       get { return allowUserToAddRows; }
+                       get { 
+                               if (allowUserToAddRows && DataManager != null)
+                                       return DataManager.AllowNew;
+                               return allowUserToAddRows;
+                       }
                        set {
                                if (allowUserToAddRows != value) {
                                        allowUserToAddRows = value;
@@ -275,7 +283,11 @@ namespace System.Windows.Forms {
 
                [DefaultValue (true)]
                public bool AllowUserToDeleteRows {
-                       get { return allowUserToDeleteRows; }
+                       get {
+                               if (allowUserToDeleteRows && DataManager != null)
+                                       return DataManager.AllowRemove;
+                               return allowUserToDeleteRows;
+                       }
                        set {
                                if (allowUserToDeleteRows != value) {
                                        allowUserToDeleteRows = value;
@@ -668,13 +680,12 @@ namespace System.Windows.Forms {
                                /// to the data cache, or the new cell is in a hidden
                                /// row.
                                /////////////////////////////////////////////////////
-                               if (value.DataGridView != this)
+                               if (value == null)
+                                       MoveCurrentCell (-1, -1, true, false, false, true);
+                               else if (value.DataGridView != this)
                                        throw new ArgumentException("The cell is not in this DataGridView.");
-
-                               if (value != null)
-                                       MoveCurrentCell (value.OwningColumn.Index, value.OwningRow.Index, true, false, false, true);
                                else
-                                       MoveCurrentCell (-1, -1, true, false, false, true);
+                                       MoveCurrentCell (value.OwningColumn.Index, value.OwningRow.Index, true, false, false, true);
                        }
                }
 
@@ -698,12 +709,9 @@ namespace System.Windows.Forms {
                        get { return dataMember; }
                        set {
                                if (dataMember != value) {
-                                       ClearBinding ();
-                                       
                                        dataMember = value;
+                                       ReBind ();
                                        OnDataMemberChanged(EventArgs.Empty);
-                                       
-                                       DoBinding ();
                                }
                        }
                }
@@ -723,12 +731,21 @@ namespace System.Windows.Forms {
                                if (!(value == null || value is IList || value is IListSource || value is IBindingList || value is IBindingListView))
                                        throw new NotSupportedException ("Type cannot be bound.");
                                        
-                               ClearBinding ();
-                               
                                dataSource = value;
+                               ReBind ();
                                OnDataSourceChanged (EventArgs.Empty);
-                               
-                               DoBinding ();
+                       }
+               }
+
+               internal CurrencyManager DataManager {
+                       get {
+                               if (DataSource != null && BindingContext != null) {
+                                       string dataMember = DataMember;
+                                       if (dataMember == null)
+                                               dataMember = String.Empty;
+                                       return (CurrencyManager) this.BindingContext[DataSource, dataMember];
+                               }
+                               return null;
                        }
                }
 
@@ -939,7 +956,7 @@ namespace System.Windows.Forms {
                [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
                public int NewRowIndex {
                        get {
-                               if (!allowUserToAddRows || ColumnCount == 0) {
+                               if (!AllowUserToAddRows || ColumnCount == 0) {
                                        return -1;
                                }
                                return rows.Count - 1;
@@ -980,7 +997,7 @@ namespace System.Windows.Forms {
                                if (value < 0) {
                                        throw new ArgumentException("RowCount must be >= 0.");
                                }
-                               if (value < 1 && allowUserToAddRows) {
+                               if (value < 1 && AllowUserToAddRows) {
                                        throw new ArgumentException("RowCount must be >= 1 if AllowUserToAddRows is true.");
                                }
                                if (dataSource != null) {
@@ -2238,7 +2255,7 @@ namespace System.Windows.Forms {
                                        return false;
                                }
                        }
-                       
+
                        DataGridViewCell cell = currentCell;
                        Type editType = cell.EditType;
                        
@@ -2252,12 +2269,6 @@ namespace System.Windows.Forms {
                        if (e.Cancel)
                                return false;
 
-                       // If the user begins an edit in the NewRow, add a new row
-                       if (CurrentCell.RowIndex == NewRowIndex) {
-                               new_row_commited = false;
-                               OnUserAddedRow (new DataGridViewRowEventArgs (Rows[NewRowIndex]));
-                       }
-               
                        cell.SetIsInEditMode (true);
                        
                        // The cell has an editing control we need to setup
@@ -2283,7 +2294,8 @@ namespace System.Windows.Forms {
                                cell.PositionEditingControl (true, true, this.GetCellDisplayRectangle (cell.ColumnIndex, cell.RowIndex, false), bounds, style, false, false, (columns [cell.ColumnIndex].DisplayIndex == 0), (cell.RowIndex == 0));
 
                                // Show the editing control
-                               EditingControlInternal.Visible = true;
+                               if (EditingControlInternal != null)
+                                       EditingControlInternal.Visible = true;
 
                                IDataGridViewEditingControl dgvEditingControl = (IDataGridViewEditingControl) EditingControlInternal;
                                if (dgvEditingControl != null) {
@@ -2305,21 +2317,21 @@ namespace System.Windows.Forms {
 
                public bool CancelEdit ()
                {
-                       if (currentCell != null && currentCell.IsInEditMode) {
-                               // The user's typing caused a new row to be created, but
-                               // now they are canceling that typing, we have to remove
-                               // the new row we added.
-                               if (!new_row_commited) {
-                                       DataGridViewRow delete_row = EditingRow;
-                                       Rows.RemoveInternal (delete_row);
-                                       editing_row = Rows[currentCell.RowIndex];
-                                       OnUserDeletedRow (new DataGridViewRowEventArgs (delete_row));
-                                       new_row_commited = true;
+                       if (currentCell != null) {
+                               if (currentCell.IsInEditMode) {
+                                       currentCell.SetIsInEditMode (false);
+                                       currentCell.DetachEditingControl ();
                                }
 
-                               currentCell.SetIsInEditMode (false);
-                               currentCell.DetachEditingControl ();
-                               OnCellEndEdit (new DataGridViewCellEventArgs (currentCell.ColumnIndex, currentCell.RowIndex));
+                               if (currentCell.RowIndex == NewRowIndex) {
+                                       if (DataManager != null)
+                                               DataManager.CancelCurrentEdit ();
+
+                                       new_row_editing = false;
+                                       PrepareEditingRow (false, false);
+                                       MoveCurrentCell (currentCell.ColumnIndex, NewRowIndex, true, false, false, true);
+                                       OnUserDeletedRow (new DataGridViewRowEventArgs (EditingRow));
+                               }
                        }
 
                        return true;
@@ -2337,28 +2349,20 @@ namespace System.Windows.Forms {
 
                public bool CommitEdit (DataGridViewDataErrorContexts context)
                {
-                       if (currentCell != null && currentCell.OwningRow.DataBoundItem != null) {
-                               Object ob = currentCell.OwningRow.DataBoundItem;
-                               PropertyDescriptor property = TypeDescriptor.GetProperties (ob)[currentCell.OwningColumn.DataPropertyName];
-                               if (property != null && !property.IsReadOnly) {
-                                       try {
-                                               object value = currentCell.Value;
-                                               if (property.Converter != null && 
-                                                   property.Converter.CanConvertFrom (value.GetType()))
-                                                       value = property.Converter.ConvertFrom (value);
-                                               property.SetValue (ob, value);
-                                               return true;
-                                       } catch (Exception exc) {
-                                               DataGridViewDataErrorEventArgs args = new DataGridViewDataErrorEventArgs (exc, currentCell.ColumnIndex, 
-                                                                                                                         currentCell.RowIndex, context);
-                                               InternalOnDataError (args);
-                                               if (args.ThrowException)
-                                                       throw exc;
-                                               return false;
-                                       }
-                               }
-                       }
+                       if (currentCell == null)
+                               return true;
 
+                       try {
+                               currentCell.Value = currentCell.ParseFormattedValue (currentCell.EditedFormattedValue, 
+                                                                                    currentCell.InheritedStyle, null, null);
+                       } catch (Exception e) {
+                               DataGridViewDataErrorEventArgs args = new DataGridViewDataErrorEventArgs (e, currentCell.ColumnIndex, currentCell.RowIndex, 
+                                                                                                         DataGridViewDataErrorContexts.Commit);
+                               OnDataError (false, args);
+                               if (args.ThrowException)
+                                       throw e;
+                               return false;
+                       }
                        return true;
                }
 
@@ -2386,7 +2390,7 @@ namespace System.Windows.Forms {
 
                        for (int index = first_row_index; index < Rows.Count; index++) {
                                DataGridViewRow row = GetRowInternal (index);
-                               if (rowTop + row.Height < ClientSize.Height) {
+                               if (rowTop + row.Height <= ClientSize.Height) {
                                        result++;
                                        rowTop += row.Height;
                                } else {
@@ -2410,24 +2414,24 @@ namespace System.Windows.Forms {
                        if (currentCell == null || !currentCell.IsInEditMode)
                                return true;
 
-                       if (EditingControl != null) {
-                               IDataGridViewEditingControl ctrl = EditingControl as IDataGridViewEditingControl;
-                               currentCell.Value = ctrl.GetEditingControlFormattedValue (DataGridViewDataErrorContexts.Commit);
-                               if (!CommitEdit (context)) {
+                       if (!CommitEdit (context)) {
+                               if (DataManager != null)
+                                       DataManager.EndCurrentEdit ();
+                               if (EditingControl != null)
                                        EditingControl.Focus ();
-                                       return false;
-                               }
-                               currentCell.DetachEditingControl ();    
-                       } else if (currentCell is IDataGridViewEditingCell) {
-                               currentCell.Value = (currentCell as IDataGridViewEditingCell).EditingCellFormattedValue;
-                               if (!CommitEdit (context))
-                                       return false;
+                               return false;
                        }
 
                        currentCell.SetIsInEditMode (false);
-                       new_row_commited = true;
+                       currentCell.DetachEditingControl ();
                        OnCellEndEdit (new DataGridViewCellEventArgs (currentCell.ColumnIndex, currentCell.RowIndex));
                        Focus ();
+                       if (currentCell.RowIndex == NewRowIndex) {
+                               new_row_editing = false;
+                               editing_row = null; // editing row becomes a real row
+                               PrepareEditingRow (true, false); // add a new editing row
+                               MoveCurrentCell (currentCell.ColumnIndex, NewRowIndex, true, false, false, true);
+                       }
                        return true;
                }
 
@@ -2953,11 +2957,10 @@ namespace System.Windows.Forms {
                        if (Rows.Count == 0)
                                return;
 
-                       IBindingList bindingList = DataSource as IBindingList;
                        if (dataGridViewColumn.IsDataBound) {
+                               IBindingList bindingList = DataManager.List as IBindingList;
                                if (bindingList != null && bindingList.SupportsSorting) {
-                                       CurrencyManager currencyManager = (CurrencyManager) this.BindingContext[DataSource];
-                                       bindingList.ApplySort (currencyManager.GetItemProperties()[dataGridViewColumn.DataPropertyName], direction);
+                                       bindingList.ApplySort (DataManager.GetItemProperties()[dataGridViewColumn.DataPropertyName], direction);
                                        dataGridViewColumn.HeaderCell.SortGlyphDirection = sortOrder;
                                }
                        } else {
@@ -3351,6 +3354,7 @@ namespace System.Windows.Forms {
                protected override void OnBindingContextChanged (EventArgs e)
                {
                        base.OnBindingContextChanged(e);
+                       ReBind();
                }
 
                protected virtual void OnBorderStyleChanged (EventArgs e)
@@ -3656,6 +3660,12 @@ namespace System.Windows.Forms {
                internal void OnColumnAddedInternal (DataGridViewColumnEventArgs e)
                {
                        if (e.Column.CellTemplate != null) {
+                               // The first column has just been added programatically instead of 
+                               // autogenerated so we need to create the rows for the first time.
+                               //
+                               if (!is_autogenerating_columns && columns.Count == 1)
+                                       ReBind ();
+
                                foreach (DataGridViewRow row in Rows)
                                        row.Cells.Add ((DataGridViewCell)e.Column.CellTemplate.Clone ());
                        }
@@ -4259,11 +4269,8 @@ namespace System.Windows.Forms {
 
                private void UpdateBindingPosition (int position)
                {
-                       if (DataSource != null && BindingContext != null) {
-                               CurrencyManager currencyManager = this.BindingContext[DataSource] as CurrencyManager;
-                               if (currencyManager != null)
-                                       currencyManager.Position = position;
-                       }
+                       if (DataManager != null)
+                               DataManager.Position = position;
                }
 
                protected override void OnMouseEnter (EventArgs e)
@@ -4626,13 +4633,19 @@ namespace System.Windows.Forms {
                                        horizontalScrollBar.Minimum = 0;
                                        horizontalScrollBar.Maximum = gridWidth;
                                        horizontalScrollBar.SmallChange = Columns[first_col_index].Width;
-                                       horizontalScrollBar.LargeChange = ClientSize.Width - rowHeadersWidth;
+                                       int largeChange = ClientSize.Width - rowHeadersWidth;
+                                       if (largeChange <= 0)
+                                               largeChange = ClientSize.Width;
+                                       horizontalScrollBar.LargeChange = largeChange;
                                }
                                if (verticalVisible) {
                                        verticalScrollBar.Minimum = 0;
                                        verticalScrollBar.Maximum = gridHeight;
                                        verticalScrollBar.SmallChange = first_row_height + 1;
-                                       verticalScrollBar.LargeChange = ClientSize.Height - columnHeadersHeight;
+                                       int largeChange = ClientSize.Height - columnHeadersHeight;
+                                       if (largeChange <= 0)
+                                               largeChange = ClientSize.Height;
+                                       verticalScrollBar.LargeChange = largeChange;
                                }
                        }
 
@@ -4815,6 +4828,8 @@ namespace System.Windows.Forms {
 
                internal void OnRowsAddedInternal (DataGridViewRowsAddedEventArgs e)
                {
+                       if (hover_cell != null && hover_cell.RowIndex >= e.RowIndex)
+                               hover_cell = null;
                        AutoResizeColumnsInternal ();
                        Invalidate ();
                        OnRowsAdded (e);
@@ -4839,9 +4854,22 @@ namespace System.Windows.Forms {
                        if (selected_columns != null)
                                selected_columns.InternalClear ();
 
-                       if (Rows.Count > 0 && Columns.Count > 0 && currentCell != null && 
-                           currentCell.RowIndex >= e.RowIndex)
-                               MoveCurrentCell (0, Math.Min (e.RowIndex, Rows.Count - 2), true, false, false, true);
+                       if (Rows.Count == 0) {
+                               MoveCurrentCell (-1, -1, true, false, false, true);
+                               hover_cell = null;
+                       } else if (Columns.Count == 0) {
+                               MoveCurrentCell (-1, -1, true, false, false, true);
+                               hover_cell = null;
+                       } else {
+                               int nextRowIndex = e.RowIndex;
+                               if (nextRowIndex >= Rows.Count)
+                                       nextRowIndex = Rows.Count - 1;
+                               MoveCurrentCell (currentCell != null ? currentCell.ColumnIndex : 0, nextRowIndex, 
+                                                true, false, false, true);
+                               if (hover_cell != null && hover_cell.RowIndex >= e.RowIndex)
+                                       hover_cell = null;
+                       }
+
                        Invalidate ();
                        OnRowsRemoved (e);
                }
@@ -4901,11 +4929,19 @@ namespace System.Windows.Forms {
 
                protected virtual void OnUserAddedRow (DataGridViewRowEventArgs e)
                {
-                       editing_row = null;
                        PrepareEditingRow (false, false);
 
-                       e = new DataGridViewRowEventArgs (editing_row);
-                       
+                       new_row_editing = true;
+                       if (DataManager != null) {
+                               // Switch the current editing row with a real one
+                               if (editing_row != null) {
+                                       Rows.RemoveInternal (editing_row);
+                                       editing_row = null;
+                               }
+                               DataManager.AddNew (); // will raise OnListPositionChanged
+                       }
+
+                       e = new DataGridViewRowEventArgs (Rows[NewRowIndex]);
                        DataGridViewRowEventHandler eh = (DataGridViewRowEventHandler)(Events [UserAddedRowEvent]);
                        if (eh != null) eh (this, e);
                }
@@ -4914,7 +4950,6 @@ namespace System.Windows.Forms {
                {
                        DataGridViewRowEventHandler eh = (DataGridViewRowEventHandler)(Events [UserDeletedRowEvent]);
                        if (eh != null) eh (this, e);
-
                }
 
                protected virtual void OnUserDeletingRow (DataGridViewRowCancelEventArgs e)
@@ -5145,9 +5180,12 @@ namespace System.Windows.Forms {
                {
                        DataGridViewCell cell = CurrentCell;
                        
-                       if (cell != null)
+                       if (cell != null) {
                                if (cell.KeyEntersEditMode (new KeyEventArgs ((Keys)m.WParam.ToInt32 ())))
                                        BeginEdit (true);
+                               if (EditingControl != null && ((Msg)m.Msg == Msg.WM_KEYDOWN || (Msg)m.Msg == Msg.WM_CHAR))
+                                       XplatUI.SendMessage (EditingControl.Handle, (Msg)m.Msg, m.WParam, m.LParam);
+                       }
 
                        return base.ProcessKeyEventArgs (ref m);
                }
@@ -5372,10 +5410,25 @@ namespace System.Windows.Forms {
                        if (cell != null && !cell.Visible)
                                throw new InvalidOperationException ("cell is not visible");
                                
+                       // Always update the current cell address property
+                       // If the row has moved it would be out of date.
+                       if (currentCell != null) {
+                               if (setAnchorCellAddress) {
+                                       anchor_cell.X = currentCell.ColumnIndex;
+                                       anchor_cell.Y = currentCell.RowIndex;
+                               }
+                               currentCellAddress.X = currentCell.ColumnIndex;
+                               currentCellAddress.Y = currentCell.RowIndex;
+                       }
+
                        if (cell != currentCell) {
                                if (currentCell != null) {
-                                       if (currentCell.IsInEditMode && !EndEdit ())
-                                               return false;
+                                       if (currentCell.IsInEditMode) {
+                                               if (!EndEdit ())
+                                                       return false;
+                                               else if (currentCell.RowIndex == NewRowIndex && new_row_editing)
+                                                       CancelEdit ();
+                                       }
                                        OnCellLeave (new DataGridViewCellEventArgs(currentCell.ColumnIndex, currentCell.RowIndex));
                                        OnRowLeave (new DataGridViewCellEventArgs (currentCell.ColumnIndex, currentCell.RowIndex));
                                }
@@ -5385,14 +5438,25 @@ namespace System.Windows.Forms {
                                        anchor_cell = new Point (columnIndex, rowIndex);
                                currentCellAddress = new Point (columnIndex, rowIndex);
 
-                               UpdateBindingPosition (currentCell.RowIndex);
-                               OnRowEnter (new DataGridViewCellEventArgs (cell.ColumnIndex, cell.RowIndex));
-                               OnCellEnter (new DataGridViewCellEventArgs(cell.ColumnIndex, cell.RowIndex));
+                               if (cell != null) {
+                                       UpdateBindingPosition (cell.RowIndex);
+                                       OnRowEnter (new DataGridViewCellEventArgs (cell.ColumnIndex, cell.RowIndex));
+                                       OnCellEnter (new DataGridViewCellEventArgs(cell.ColumnIndex, cell.RowIndex));
+                               }
                                OnCurrentCellChanged (EventArgs.Empty);
-                               if (throughMouseClick || editMode == DataGridViewEditMode.EditOnEnter)
-                                       BeginEdit (true);
+
+                               if (cell != null) {
+                                       // If the user begins an edit in the NewRow, add a new row
+                                       if (AllowUserToAddRows && cell.RowIndex == NewRowIndex && !is_binding && !new_row_editing) {
+                                               // OnUserAddedRow will add a real row and reset the current cell
+                                               OnUserAddedRow (new DataGridViewRowEventArgs (Rows[NewRowIndex]));
+                                       } else {
+                                               if (editMode == DataGridViewEditMode.EditOnEnter)
+                                                       BeginEdit (true);
+                                       }
+                               }
                        } else {
-                               if (throughMouseClick)
+                               if (cell != null && throughMouseClick)
                                        BeginEdit (true);
                        }
 
@@ -5430,7 +5494,8 @@ namespace System.Windows.Forms {
                }
 
                internal void SetSelectedRowCoreInternal (int rowIndex, bool selected) {
-                       SetSelectedRowCore (rowIndex, selected);
+                       if (rowIndex >= 0 && rowIndex < Rows.Count)
+                               SetSelectedRowCore (rowIndex, selected);
                }       
 
                protected virtual void SetSelectedRowCore (int rowIndex, bool selected) {
@@ -5724,6 +5789,9 @@ namespace System.Windows.Forms {
 
                internal void PrepareEditingRow (bool cell_changed, bool column_changed)
                {
+                       if (new_row_editing)
+                               return;
+
                        bool show = false;
                        
                        show = ColumnCount > 0 && AllowUserToAddRows;
@@ -5732,86 +5800,24 @@ namespace System.Windows.Forms {
                                Rows.RemoveInternal (editing_row);
                                editing_row = null;
                        } else if (show) {
-                               if (editing_row != null) {
-                                       if (cell_changed) {
-                                               // The row changed, it's no longer an editing row.
-                                               editing_row = null;
-                                       } else if (column_changed) {
-                                               // The number of columns has changed, we need a new editing row.
-                                               Rows.RemoveInternal (editing_row);
-                                               editing_row = null;
-                                       }
+                               if (editing_row != null && (cell_changed || column_changed)) {
+                                       // The row changed, it's no longer an editing row.
+                                       //    or
+                                       // The number of columns has changed, we need a new editing row.
+                                       Rows.RemoveInternal (editing_row);
+                                       editing_row = null;
                                }
                                if (editing_row == null) {
                                        editing_row = RowTemplateFull;
                                        Rows.AddInternal (editing_row, false);
                                }
                        }
-                               
-                       
                }
                
                internal DataGridViewRow EditingRow {
                        get { return editing_row; }
                }
 
-               private void BindIList (IList list) {
-                       if (autoGenerateColumns) {
-                               // Stuff from a DataSet
-                               if (list is DataView) {
-                                       DataView dataView = (DataView) list;
-                                       DataTable table = dataView.Table;
-
-                                       foreach (DataColumn dataColumn in table.Columns) {
-                                               DataGridViewColumn col = CreateColumnByType (dataColumn.DataType);
-                                               
-                                               col.Name = dataColumn.ColumnName;
-                                               col.DataPropertyName = dataColumn.ColumnName;
-                                               col.SetIsDataBound (true);
-                                               col.ValueType = dataColumn.DataType;
-                                               col.AutoGenerated = true;
-                                               
-                                               columns.Add (col);
-                                       }
-                               }
-                               // Its a generic something or other, like a BindingList<T>, so
-                               // we can figure out the type from the generic type
-                               else if (list.GetType ().GetGenericArguments ().Length > 0) {
-                                       GenerateColumnsFromType (list.GetType ().GetGenericArguments ()[0]);
-                               }
-                               // Its a normal array/collection type thing
-                               else if (list.GetType ().IsArray) {
-                                       GenerateColumnsFromType (list.GetType ().GetElementType ());
-                               } else if (list is BindingSource && (list as BindingSource).item_type != null) {
-                                       foreach (PropertyDescriptor property in TypeDescriptor.GetProperties ((list as BindingSource).item_type)) {
-                                               DataGridViewColumn col = CreateColumnByType (property.PropertyType);
-                                               col.Name = property.DisplayName;
-                                               col.ReadOnly = property.IsReadOnly;
-                                               col.AutoGenerated = true;
-                                               columns.Add (col);
-                                       }
-
-                                       AllowUserToAddRows = (list as BindingSource).AllowNew;
-                               }
-                       }
-               
-                       // Subscribe to the dataset's change notification
-                       if (list is DataView) {
-                               (list as DataView).ListChanged += OnListChanged;
-                               (list as DataView).Table.ColumnChanged += OnTableColumnChanged;
-                               (list as DataView).Table.TableCleared += OnTableCleared;
-                       }
-
-                       // Add the rows
-                       foreach (object element in list)
-                               AddBoundRow (element);
-               }
-
-               private void OnBindingSourceDataSourceChanged (object sender, EventArgs args)
-               {
-                       ReBind ();
-               }
-
                private void AddBoundRow (object element)
                {
                        // Don't add rows if there are no columns
@@ -5834,29 +5840,20 @@ namespace System.Windows.Forms {
                                if (cell == null)
                                        continue;
                                        
-                               cell.valuex = property.GetValue (element);
-                               cell.valueType = property.PropertyType;
+                               cell.Value = property.GetValue (element);
+                               cell.ValueType = property.PropertyType;
                        }
                }
                
-               private void GenerateColumnsFromType (Type type)
+               private bool IsColumnAlreadyBound (string name)
                {
-                       foreach (PropertyDescriptor property in TypeDescriptor.GetProperties (type)) {
-                               // This keeps out things like arrays
-                               if ((typeof(ICollection).IsAssignableFrom (property.PropertyType)))
-                                       continue;
-                                       
-                               DataGridViewColumn col = CreateColumnByType (property.PropertyType);
-                               col.Name = property.DisplayName;
-                               col.DataPropertyName = property.DisplayName;
-                               col.ReadOnly = property.IsReadOnly;
-                               col.SetIsDataBound (true);
-                               col.ValueType = property.PropertyType;
-                               col.AutoGenerated = true;
-                               columns.Add (col);
-                       }
+                       foreach (DataGridViewColumn col in Columns)
+                               if (col.DataPropertyName == name)
+                                       return true;
+
+                       return false;
                }
-               
+
                private DataGridViewColumn CreateColumnByType (Type type)
                {
                        if (type == typeof (bool))
@@ -5867,34 +5864,12 @@ namespace System.Windows.Forms {
                
                private void ClearBinding ()
                {
-                       columns.ClearAutoGeneratedColumns ();
-                       rows.Clear ();
-                       PrepareEditingRow (false, true);
-
-                       if (dataSource != null) {
-                               if (dataSource is DataSet) {
-                                       (dataSource as DataSet).Tables.CollectionChanged -= OnDataSetTableChanged;
-                                       
-                                       DataTable dt = (dataSource as DataSet).Tables[dataMember];
-                                       
-                                       if (dt != null) {
-                                               DataView dv = dt.DefaultView;
-                                       
-                                               if (dv != null) {
-                                                       (dv as DataView).Table.ColumnChanged -= OnTableColumnChanged;
-                                                       (dv as DataView).ListChanged -= OnListChanged;
-                                               }
-                                       }
-                               } else if (dataSource is DataView) {
-                                       (dataSource as DataView).ListChanged -= OnListChanged;
-                                       (dataSource as DataView).Table.ColumnChanged -= OnTableColumnChanged;
-                               } else if (dataSource is DataTable)
-                                       ((dataSource as IListSource).GetList () as DataView).ListChanged -= OnListChanged;
-
-                               if (dataSource is IBindingList)
-                                       (dataSource as IBindingList).ListChanged -= OnListChanged;
-                               if (dataSource is BindingSource)
-                                       (dataSource as BindingSource).DataSourceChanged -= OnBindingSourceDataSourceChanged;
+                       if (DataManager != null) {
+                               columns.ClearAutoGeneratedColumns ();
+                               PrepareEditingRow (false, true);
+                               rows.Clear ();
+                               DataManager.ListChanged -= OnListChanged;
+                               DataManager.PositionChanged -= OnListPositionChanged;
                        }
                }
                
@@ -5907,62 +5882,68 @@ namespace System.Windows.Forms {
                         - the System.ComponentModel.IBindingListView interface, such as the System.Windows.Forms.BindingSource class.
                        */
                        
-                       if (dataSource != null) {
-                               object value = dataSource;
-                               
-                               // DataBinding
-                               if (value is DataSet && string.IsNullOrEmpty (dataMember)) {
-                                       Invalidate ();
-                                       return;
+                       if (dataSource != null && DataManager != null) {
+                               if (autoGenerateColumns) {
+                                       is_autogenerating_columns = true;
+
+                                       foreach (PropertyDescriptor property in DataManager.GetItemProperties()) {
+                                               // This keeps out things like arrays
+                                               if ((typeof(ICollection).IsAssignableFrom (property.PropertyType)))
+                                                       continue;
+
+                                               if (IsColumnAlreadyBound (property.DisplayName))
+                                                       continue;
+
+                                               DataGridViewColumn col = CreateColumnByType (property.PropertyType);
+                                               col.Name = property.DisplayName;
+                                               col.DataPropertyName = property.DisplayName;
+                                               col.ReadOnly = !DataManager.AllowEdit || property.IsReadOnly;
+                                               col.SetIsDataBound (true);
+                                               col.ValueType = property.PropertyType;
+                                               col.AutoGenerated = true;
+                                               columns.Add (col);
+                                       }
+
+                                       is_autogenerating_columns = false;
                                }
-                               if (value is DataSet) {
-                                       (value as DataSet).Tables.CollectionChanged += OnDataSetTableChanged;
-                                       value = (value as DataSet).Tables[dataMember];
+
+                               // DataBind both autogenerated and not columns if there is a matching property
+                               foreach (PropertyDescriptor property in DataManager.GetItemProperties()) {
+                                       foreach (DataGridViewColumn col in Columns) {
+                                               if (col.DataPropertyName == property.Name)
+                                                       col.SetIsDataBound (true);
+                                       }
                                }
-                               
-                               if (value is BindingSource)
-                                       BindBindingSource (value as BindingSource);
-                               else if (value is IBindingListView)
-                                       BindIBindingListView (value as IBindingListView);
-                               else if (value is IBindingList)
-                                       BindIBindingList (value as IBindingList);
-                               else if (value is IList)
-                                       BindIList (value as IList);
-                               else if (value is IListSource)
-                                       BindIListSource (value as IListSource);
 
+                               foreach (object element in DataManager.List)
+                                       AddBoundRow (element);
+
+                               DataManager.ListChanged += OnListChanged;
+                               DataManager.PositionChanged += OnListPositionChanged;
                                OnDataBindingComplete (new DataGridViewBindingCompleteEventArgs (ListChangedType.Reset));
+                               OnListPositionChanged (this, EventArgs.Empty);
+                       } else {
+                               if (Rows.Count > 0 && Columns.Count > 0)
+                                       MoveCurrentCell (0, 0, true, false, false, false);
                        }
-                       if (Rows.Count > 0 && Columns.Count > 0)
-                               MoveCurrentCell (0, 0, true, false, false, false);
+
                        PerformLayout();
                        Invalidate ();
                }
                
-               private void BindBindingSource (BindingSource bindingSource)
-               {
-                       BindIList (bindingSource.List);
-                       bindingSource.ListChanged += OnBindingSourceDataSourceChanged;
-                       bindingSource.DataSourceChanged += OnBindingSourceDataSourceChanged;
-               }
-
-               private void BindIListSource (IListSource list) {
-                       BindIList (list.GetList());
-               }
-
-               private void BindIBindingList (IBindingList list) {
-                       BindIList (list);
-                       list.ListChanged += OnListChanged;
-               }
-
-               private void BindIBindingListView (IBindingListView list) {
-                       BindIList(list);
-               }
-
                private void MoveCurrentCell (int x, int y, bool select, bool isControl, bool isShift, bool scroll)
                {
-                       if (!SetCurrentCellAddressCore (x, y, true, false, false))
+                       if (x == -1 || y == -1)
+                               x = y = -1;
+
+                       if (!SetCurrentCellAddressCore (x, y, true, false, false)) {
+                               ClearSelection ();
                                return;
+                       }
+                       if (x == -1 && y == -1) {
+                               ClearSelection ();
+                               return;
+                       }
 
                        bool full_row_selected = Rows.SharedRow(CurrentCellAddress.Y).Selected;
                        bool full_col_selected = Columns[CurrentCellAddress.X].Selected;
@@ -6048,6 +6029,8 @@ namespace System.Windows.Forms {
                
                private int ColumnIndexToDisplayIndex (int index)
                {
+                       if (index == -1)
+                               return index;
                        return Columns[index].DisplayIndex;
                }
                
@@ -6060,10 +6043,12 @@ namespace System.Windows.Forms {
                {
                        switch (args.ListChangedType) {
                                case ListChangedType.ItemAdded:
-                                       AddBoundRow ((sender as IBindingList)[args.NewIndex]);
+                                       AddBoundRow (DataManager[args.NewIndex]);
                                        break;
                                case ListChangedType.ItemDeleted:
-                                       Rows.RemoveAt (args.NewIndex);
+                                       Rows.RemoveAtInternal (args.NewIndex);
+                                       break;
+                               case ListChangedType.ItemChanged:
                                        break;
                                default:
                                        ReBind ();
@@ -6073,25 +6058,23 @@ namespace System.Windows.Forms {
                        Invalidate ();
                }
                
-               private void OnTableColumnChanged (object sender, DataColumnChangeEventArgs e)
+               private void OnListPositionChanged (object sender, EventArgs args)
                {
-                       ReBind ();
-               }
-
-               private void OnDataSetTableChanged (object sender, CollectionChangeEventArgs e)
-               {
-                       ReBind ();
-               }
-
-               private void OnTableCleared (object sender, DataTableClearEventArgs e)
-               {
-                       ReBind ();
+                       if (Rows.Count > 0 && Columns.Count > 0 && DataManager.Position != -1)
+                               MoveCurrentCell (currentCell != null ? currentCell.ColumnIndex : 0, DataManager.Position, 
+                                                true, false, false, true);
+                       else
+                               MoveCurrentCell (-1, -1, true, false, false, true);
                }
 
                private void ReBind ()
                {
-                       ClearBinding ();
-                       DoBinding ();
+                       if (!is_binding) {
+                               is_binding = true;
+                               ClearBinding ();
+                               DoBinding ();
+                               is_binding = false;
+                       }
                }
                
                private bool MouseOverColumnResize (int col, int mousex)
@@ -6201,16 +6184,18 @@ namespace System.Windows.Forms {
                                DataGridViewRow row2 = (DataGridViewRow)y;
 
                                if (row1.Cells[column].ValueType == typeof (DateTime) && row2.Cells[column].ValueType == typeof (DateTime))
-                                       return DateTime.Compare ((DateTime)row1.Cells[column].valuex, (DateTime)row2.Cells[column].valuex) * direction;
+                                       return DateTime.Compare ((DateTime)row1.Cells[column].Value, (DateTime)row2.Cells[column].Value) * direction;
 
                                object val1 = row1.Cells[column].FormattedValue;
                                object val2 = row2.Cells[column].FormattedValue;
+                               object val1NullValue = row1.Cells[column].InheritedStyle.NullValue;
+                               object val2NullValue = row2.Cells[column].InheritedStyle.NullValue;
 
-                               if (val1 == null && val2 == null)
+                               if (val1 == val1NullValue && val2 == val2NullValue)
                                        return 0;
-                               if (val1 == null)
+                               if (val1 == val1NullValue)
                                        return direction;
-                               if (val2 == null)
+                               if (val2 == val2NullValue)
                                        return -1 * direction;
 
                                if (numeric_sort)