Requires gmcs
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / DataGrid.cs
index fbc6e246d3587a43f4591008a071dc4c7e2df6cf..b489ce5f0a89d5a31b7ab63769d95778aba6b893 100644 (file)
@@ -25,9 +25,6 @@
 //
 //
 
-// NOT COMPLETE
-
-
 using System;
 using System.ComponentModel;
 using System.Data;
@@ -114,10 +111,17 @@ namespace System.Windows.Forms
        [DefaultEvent("Navigate")]
        [DefaultProperty("DataSource")]
        [Designer("System.Windows.Forms.Design.DataGridDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
+#if NET_2_0
+       [ComplexBindingProperties ("DataSource", "DataMember")]
+       [ClassInterface (ClassInterfaceType.AutoDispatch)]
+       [ComVisible (true)]
+#endif
        public class DataGrid : Control, ISupportInitialize, IDataGridEditingService
        {
                [Flags]
+#if !NET_2_0
                [Serializable]
+#endif
                public enum HitTestType
                {
                        None            = 0,
@@ -165,12 +169,12 @@ namespace System.Windows.Forms
                        }
                        #endregion //Public Instance Properties
 
-                       public override bool Equals (object o)
+                       public override bool Equals (object value)
                        {
-                               if (!(o is HitTestInfo))
+                               if (!(value is HitTestInfo))
                                        return false;
 
-                               HitTestInfo obj = (HitTestInfo) o;
+                               HitTestInfo obj = (HitTestInfo) value;
                                return (obj.Column == column && obj.Row == row && obj.Type ==type);
                        }
 
@@ -183,7 +187,6 @@ namespace System.Windows.Forms
                        {
                                return "{ " + type + "," + row + "," + column + "}";
                        }
-
                }
 
                #region Local Variables
@@ -191,23 +194,23 @@ namespace System.Windows.Forms
                static readonly Color   def_background_color = ThemeEngine.Current.DataGridBackgroundColor;
                static readonly Color   def_caption_backcolor = ThemeEngine.Current.DataGridCaptionBackColor;
                static readonly Color   def_caption_forecolor = ThemeEngine.Current.DataGridCaptionForeColor;
-               static readonly Color   def_parentrowsback_color = ThemeEngine.Current.DataGridParentRowsBackColor;
-               static readonly Color   def_parentrowsfore_color = ThemeEngine.Current.DataGridParentRowsForeColor;
+               static readonly Color   def_parent_rows_backcolor = ThemeEngine.Current.DataGridParentRowsBackColor;
+               static readonly Color   def_parent_rows_forecolor = ThemeEngine.Current.DataGridParentRowsForeColor;
 
                /* colors */
                // XXX this needs addressing. Control.background_color should not be internal.
                new Color background_color;
                Color caption_backcolor;
                Color caption_forecolor;
-               Color parentrowsback_color;
-               Color parentrowsfore_color;
+               Color parent_rows_backcolor;
+               Color parent_rows_forecolor;
 
                /* flags to determine which areas of the datagrid are shown */
                bool caption_visible;
-               bool parentrows_visible;
+               bool parent_rows_visible;
 
                GridTableStylesCollection styles_collection;
-               DataGridParentRowsLabelStyle parentrowslabel_style;
+               DataGridParentRowsLabelStyle parent_rows_label_style;
                DataGridTableStyle default_style;
                DataGridTableStyle grid_style;
                DataGridTableStyle current_style;
@@ -219,10 +222,10 @@ namespace System.Windows.Forms
 
                /* layout/rendering */
                bool allow_navigation;
-               int first_visiblerow;
-               int first_visiblecolumn;
-               int visiblerow_count;
-               int visiblecolumn_count;
+               int first_visible_row;
+               int first_visible_column;
+               int visible_row_count;
+               int visible_column_count;
                Font caption_font;
                string caption_text;
                bool flatmode;
@@ -263,12 +266,13 @@ namespace System.Windows.Forms
                bool from_positionchanged_handler;
 
                /* editing state */
+               internal bool pending_new_row;
                bool cursor_in_add_row;
                bool add_row_changed;
-               bool is_editing;                // Current cell is edit mode
+               internal bool is_editing;               // Current cell is edit mode
                bool is_changing;
 
-               internal Stack dataSourceStack;
+               internal Stack data_source_stack;
 
                #endregion // Local Variables
 
@@ -283,11 +287,11 @@ namespace System.Windows.Forms
                        caption_text = string.Empty;
                        caption_visible = true;
                        datamember = string.Empty;
-                       parentrowsback_color = def_parentrowsback_color;
-                       parentrowsfore_color = def_parentrowsfore_color;
-                       parentrows_visible = true;
+                       parent_rows_backcolor = def_parent_rows_backcolor;
+                       parent_rows_forecolor = def_parent_rows_forecolor;
+                       parent_rows_visible = true;
                        current_cell = new DataGridCell ();
-                       parentrowslabel_style = DataGridParentRowsLabelStyle.Both;
+                       parent_rows_label_style = DataGridParentRowsLabelStyle.Both;
                        selected_rows = new Hashtable ();
                        selection_start = -1;
                        rows = new DataGridRelationshipRow [0];
@@ -307,12 +311,12 @@ namespace System.Windows.Forms
 
                        SetStyle (ControlStyles.UserMouse, true);
 
-                       dataSourceStack = new Stack ();
+                       data_source_stack = new Stack ();
 
                        back_button_image = ResourceImageLoader.Get ("go-previous.png");
-                       //back_button_image.MakeTransparent (Color.Transparent);
+                       back_button_image.MakeTransparent (Color.Transparent);
                        parent_rows_button_image = ResourceImageLoader.Get ("go-top.png");
-                       //parent_rows_button_image.MakeTransparent (Color.Transparent);
+                       parent_rows_button_image.MakeTransparent (Color.Transparent);
                }
 
                #endregion      // Public Constructor
@@ -336,7 +340,7 @@ namespace System.Windows.Forms
                        set { grid_style.AllowSorting = value; }
                }
 
-               public Color AlternatingBackColor  {
+               public Color AlternatingBackColor {
                        get { return grid_style.AlternatingBackColor; }
                        set { grid_style.AlternatingBackColor = value; }
                }
@@ -365,11 +369,20 @@ namespace System.Windows.Forms
                                if (base.BackgroundImage == value)
                                        return;
 
-                               base.BackgroundImage = value;
+                               base.BackgroundImage = value;
                                Invalidate ();
                        }
                }
 
+#if NET_2_0
+               [Browsable (false)]
+               [EditorBrowsable (EditorBrowsableState.Never)]
+               public override ImageLayout BackgroundImageLayout {
+                       get { return base.BackgroundImageLayout; }
+                       set { base.BackgroundImageLayout = value; }
+               }
+#endif
+
                [DispId(-504)]
                [DefaultValue(BorderStyle.Fixed3D)]
                public BorderStyle BorderStyle {
@@ -447,7 +460,16 @@ namespace System.Windows.Forms
                [DefaultValue(true)]
                public bool ColumnHeadersVisible {
                        get { return grid_style.ColumnHeadersVisible; }
-                       set { grid_style.ColumnHeadersVisible = value; }
+                       set { 
+                               if (grid_style.ColumnHeadersVisible != value) {
+                                       grid_style.ColumnHeadersVisible = value; 
+
+#if NET_2_0
+                                       // UIA Framework: To keep track of header
+                                       OnUIAColumnHeadersVisibleChanged ();
+#endif
+                               }
+                       }
                }
 
                bool setting_current_cell;
@@ -479,6 +501,11 @@ namespace System.Windows.Forms
                                if (value.ColumnNumber >= CurrentTableStyle.GridColumnStyles.Count)
                                        value.ColumnNumber = CurrentTableStyle.GridColumnStyles.Count == 0 ? 0 : CurrentTableStyle.GridColumnStyles.Count - 1;
 
+
+                               /* now make sure we don't go negative */
+                               if (value.RowNumber < 0) value.RowNumber = 0;
+                               if (value.ColumnNumber < 0) value.ColumnNumber = 0;
+
                                bool was_changing = is_changing;
 
                                add_row_changed = add_row_changed || was_changing;
@@ -494,6 +521,9 @@ namespace System.Windows.Forms
                                                                                          "Error when committing the row to the original data source",
                                                                                          MessageBoxButtons.YesNo);
                                                        if (r == DialogResult.Yes) {
+                                                               InvalidateRowHeader (value.RowNumber);
+                                                               InvalidateRowHeader (current_cell.RowNumber);
+                                                               setting_current_cell = false;
                                                                Edit ();
                                                                return;
                                                        }
@@ -502,24 +532,25 @@ namespace System.Windows.Forms
                                                }
                                        }
 
-                                       if (value.RowNumber == RowsCount && !ListManager.CanAddRows)
+                                       if (value.RowNumber == RowsCount && !ListManager.AllowNew)
                                                value.RowNumber --;
-
-                                       if (value.RowNumber == RowsCount) {
-                                               cursor_in_add_row = true;
-                                               add_row_changed = false;
-                                               AddNewRow ();
-                                       }
-                                       else {
-                                               cursor_in_add_row = false;
-                                       }
                                }
 
                                int old_row = current_cell.RowNumber;
 
+                               current_cell = value;
+
                                EnsureCellVisibility (value);
 
-                               current_cell = value;
+                               if (CurrentRow == RowsCount && ListManager.AllowNew) {
+                                       cursor_in_add_row = true;
+                                       add_row_changed = false;
+                                       pending_new_row = true;
+                               }
+                               else {
+                                       cursor_in_add_row = false;
+                                       pending_new_row = false;
+                               }
 
                                InvalidateRowHeader (old_row);
                                InvalidateRowHeader (current_cell.RowNumber);
@@ -583,7 +614,11 @@ namespace System.Windows.Forms
 
                [DefaultValue(null)]
                [RefreshProperties(RefreshProperties.Repaint)]
+#if NET_2_0
+               [AttributeProvider (typeof (IListSource))]
+#else
                [TypeConverter("System.Windows.Forms.Design.DataSourceConverter, " + Consts.AssemblySystem_Design)]
+#endif
                public object DataSource {
                        get { return datasource; }
                        set {
@@ -608,7 +643,7 @@ namespace System.Windows.Forms
 
                [Browsable(false)]
                public int FirstVisibleColumn {
-                       get { return first_visiblecolumn; }
+                       get { return first_visible_column; }
                }
 
                [DefaultValue(false)]
@@ -687,8 +722,17 @@ namespace System.Windows.Forms
                public object this [int rowIndex, int columnIndex] {
                        get { return CurrentTableStyle.GridColumnStyles[columnIndex].GetColumnValueAtRow (ListManager,
                                                                                                          rowIndex); }
-                       set { CurrentTableStyle.GridColumnStyles[columnIndex].SetColumnValueAtRow (ListManager,
-                                                                                                  rowIndex, value); }
+                       set { 
+                               CurrentTableStyle.GridColumnStyles[columnIndex].SetColumnValueAtRow (ListManager,
+                                                                                                    rowIndex, value); 
+
+#if NET_2_0
+                               // UIA Framework: Raising changes in datasource.
+                               OnUIAGridCellChanged (new CollectionChangeEventArgs (CollectionChangeAction.Refresh,
+                                                                                    new DataGridCell (rowIndex,
+                                                                                                      columnIndex)));
+#endif
+                       }
                }
 
                public Color LinkColor {
@@ -700,7 +744,9 @@ namespace System.Windows.Forms
                        get { return new Font (Font, FontStyle.Underline); }
                }
 
+#if !NET_2_0
                [ComVisible(false)]
+#endif
                [Browsable(false)]
                [EditorBrowsable(EditorBrowsableState.Never)]
                public Color LinkHoverColor {
@@ -723,11 +769,11 @@ namespace System.Windows.Forms
                }
 
                public Color ParentRowsBackColor {
-                       get { return parentrowsback_color; }
+                       get { return parent_rows_backcolor; }
                        set {
-                               if (parentrowsback_color != value) {
-                                       parentrowsback_color = value;
-                                       if (parentrows_visible) {
+                               if (parent_rows_backcolor != value) {
+                                       parent_rows_backcolor = value;
+                                       if (parent_rows_visible) {
                                                Refresh ();
                                        }
                                }
@@ -735,11 +781,11 @@ namespace System.Windows.Forms
                }
 
                public Color ParentRowsForeColor {
-                       get { return parentrowsfore_color; }
+                       get { return parent_rows_forecolor; }
                        set {
-                               if (parentrowsfore_color != value) {
-                                       parentrowsfore_color = value;
-                                       if (parentrows_visible) {
+                               if (parent_rows_forecolor != value) {
+                                       parent_rows_forecolor = value;
+                                       if (parent_rows_visible) {
                                                Refresh ();
                                        }
                                }
@@ -749,11 +795,11 @@ namespace System.Windows.Forms
                [DefaultValue(DataGridParentRowsLabelStyle.Both)]
                [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
                public DataGridParentRowsLabelStyle ParentRowsLabelStyle {
-                       get { return parentrowslabel_style; }
+                       get { return parent_rows_label_style; }
                        set {
-                               if (parentrowslabel_style != value) {
-                                       parentrowslabel_style = value;
-                                       if (parentrows_visible) {
+                               if (parent_rows_label_style != value) {
+                                       parent_rows_label_style = value;
+                                       if (parent_rows_visible) {
                                                Refresh ();
                                        }
 
@@ -764,10 +810,10 @@ namespace System.Windows.Forms
 
                [DefaultValue(true)]
                public bool ParentRowsVisible {
-                       get { return parentrows_visible; }
+                       get { return parent_rows_visible; }
                        set {
-                               if (parentrows_visible != value) {
-                                       parentrows_visible = value;
+                               if (parent_rows_visible != value) {
+                                       parent_rows_visible = value;
                                        CalcAreasAndInvalidate ();
                                        OnParentRowsVisibleChanged (EventArgs.Empty);
                                }
@@ -821,7 +867,7 @@ namespace System.Windows.Forms
                        set { grid_style.SelectionBackColor = value; }
                }
 
-               public Color SelectionForeColor  {
+               public Color SelectionForeColor {
                        get { return grid_style.SelectionForeColor; }
                        set { grid_style.SelectionForeColor = value; }
                }
@@ -857,12 +903,12 @@ namespace System.Windows.Forms
 
                [Browsable(false)]
                public int VisibleColumnCount {
-                       get { return visiblecolumn_count; }
+                       get { return visible_column_count; }
                }
 
                [Browsable(false)]
                public int VisibleRowCount {
-                       get { return visiblerow_count; }
+                       get { return visible_row_count; }
                }
 
                #endregion      // Public Instance Properties
@@ -887,7 +933,7 @@ namespace System.Windows.Forms
                }
 
                internal int FirstVisibleRow {
-                       get { return first_visiblerow; }
+                       get { return first_visible_row; }
                }
                
                internal int RowsCount {
@@ -903,9 +949,13 @@ namespace System.Windows.Forms
                        }
                }
                
+               internal override bool ScaleChildrenInternal {
+                       get { return false; }
+               }
+
                internal bool ShowEditRow {
                        get {
-                               if (ListManager != null && !ListManager.CanAddRows)
+                               if (ListManager != null && !ListManager.AllowNew)
                                        return false;
 
                                return !_readonly;
@@ -913,7 +963,7 @@ namespace System.Windows.Forms
                }
                
                internal bool ShowParentRows {
-                       get { return ParentRowsVisible && dataSourceStack.Count > 0; }
+                       get { return ParentRowsVisible && data_source_stack.Count > 0; }
                }
                
                #endregion Private Instance Properties
@@ -929,7 +979,6 @@ namespace System.Windows.Forms
                        }
                }
 
-               [MonoTODO]
                public bool BeginEdit (DataGridColumnStyle gridColumn, int rowNumber)
                {
                        if (is_changing)
@@ -972,7 +1021,6 @@ namespace System.Windows.Forms
                        is_editing = false;
                }
 
-               [MonoTODO]
                public void Collapse (int row)
                {
                        if (!rows[row].IsExpanded)
@@ -988,7 +1036,7 @@ namespace System.Windows.Forms
                        ResumeLayout (false);
 
                        /* XX need to redraw from @row down */
-                       CalcAreasAndInvalidate ();                      
+                       CalcAreasAndInvalidate ();
                }
 
                protected internal virtual void ColumnStartedEditing (Control editingControl)
@@ -1020,6 +1068,7 @@ namespace System.Windows.Forms
                        return CreateGridColumn (prop, false);
                }
 
+               [MonoTODO ("Not implemented, will throw NotImplementedException")]
                protected virtual DataGridColumnStyle CreateGridColumn (PropertyDescriptor prop, bool isDefault)
                {
                        throw new NotImplementedException();
@@ -1032,7 +1081,7 @@ namespace System.Windows.Forms
 
                public bool EndEdit (DataGridColumnStyle gridColumn, int rowNumber, bool shouldAbort)
                {
-                       if (shouldAbort || gridColumn.ParentReadOnly)
+                       if (shouldAbort || (_readonly || gridColumn.TableStyleReadOnly || gridColumn.ReadOnly))
                                gridColumn.Abort (rowNumber);
                        else {
                                gridColumn.Commit (ListManager, rowNumber);
@@ -1049,6 +1098,8 @@ namespace System.Windows.Forms
 
                public void EndInit ()
                {
+                       if (grid_style != null)
+                               grid_style.DataGrid = this;
                }
 
                public void Expand (int row)
@@ -1071,7 +1122,7 @@ namespace System.Windows.Forms
                        }
                        string relation_text = relation_builder.ToString ();
 
-                       SizeF measured_area = DeviceContext.MeasureString (relation_text, LinkFont);
+                       SizeF measured_area = TextRenderer.MeasureString (relation_text, LinkFont);
 
                        rows[row].relation_area = new Rectangle (cells_area.X + 1,
                                                                 0, /* updated as needed at the usage sites for relation_area */
@@ -1087,9 +1138,9 @@ namespace System.Windows.Forms
                        CalcAreasAndInvalidate ();
                }
 
-               public Rectangle GetCellBounds (DataGridCell cell)
+               public Rectangle GetCellBounds (DataGridCell dgc)
                {
-                       return GetCellBounds (cell.RowNumber, cell.ColumnNumber);
+                       return GetCellBounds (dgc.RowNumber, dgc.ColumnNumber);
                }
 
                public Rectangle GetCellBounds (int row, int col)
@@ -1127,18 +1178,18 @@ namespace System.Windows.Forms
 
                protected virtual void GridVScrolled (object sender, ScrollEventArgs se)
                {
-                       int old_first_visiblerow = first_visiblerow;
-                       first_visiblerow = se.NewValue;
+                       int old_first_visible_row = first_visible_row;
+                       first_visible_row = se.NewValue;
 
-                       if (first_visiblerow == old_first_visiblerow)
+                       if (first_visible_row == old_first_visible_row)
                                return;
 
                        UpdateVisibleRowCount ();
 
-                       if (first_visiblerow == old_first_visiblerow)
+                       if (first_visible_row == old_first_visible_row)
                                return;
                        
-                       ScrollToRow (old_first_visiblerow, first_visiblerow);
+                       ScrollToRow (old_first_visible_row, first_visible_row);
                }
 
                public HitTestInfo HitTest (Point position)
@@ -1152,11 +1203,14 @@ namespace System.Windows.Forms
                // From Point to Cell
                public HitTestInfo HitTest (int x, int y)
                {
-                       if (columnhdrs_area.Contains (x, y)) {
+                       if (column_headers_area.Contains (x, y)) {
                                int offset_x = x + horiz_pixeloffset;
                                int column_x;
                                int column_under_mouse = FromPixelToColumn (offset_x, out column_x);
-                               
+
+                               if (column_under_mouse == -1)
+                                       return new HitTestInfo (-1, -1, HitTestType.None);
+
                                if ((column_x + CurrentTableStyle.GridColumnStyles[column_under_mouse].Width - offset_x < RESIZE_HANDLE_HORIZ_SIZE)
                                    && column_under_mouse < CurrentTableStyle.GridColumnStyles.Count) {
 
@@ -1167,7 +1221,7 @@ namespace System.Windows.Forms
                                }
                        }
 
-                       if (rowhdrs_area.Contains (x, y)) {
+                       if (row_headers_area.Contains (x, y)) {
                                int posy;
                                int rcnt = FirstVisibleRow + VisibleRowCount;
                                for (int r = FirstVisibleRow; r < rcnt; r++) {
@@ -1198,9 +1252,9 @@ namespace System.Windows.Forms
                                pos_y = cells_area.Y + rows[row].VerticalOffset - rows[FirstVisibleRow].VerticalOffset;
                                if (y <= pos_y + rows[row].Height) {
                                        int col_pixel;
-                                       int column_cnt = first_visiblecolumn + visiblecolumn_count;
+                                       int column_cnt = first_visible_column + visible_column_count;
                                        if (column_cnt > 0) {
-                                               for (int column = first_visiblecolumn; column < column_cnt; column++) {
+                                               for (int column = first_visible_column; column < column_cnt; column++) {
                                                        if (CurrentTableStyle.GridColumnStyles[column].bound == false)
                                                                continue;
                                                        col_pixel = GetColumnStartingPixel (column);
@@ -1235,13 +1289,12 @@ namespace System.Windows.Forms
                        return rows[row].IsSelected;
                }
 
-               [MonoTODO]
                public void NavigateBack ()
                {
-                       if (dataSourceStack.Count == 0)
+                       if (data_source_stack.Count == 0)
                                return;
 
-                       DataGridDataSource source = (DataGridDataSource)dataSourceStack.Pop ();
+                       DataGridDataSource source = (DataGridDataSource)data_source_stack.Pop ();
                        list_manager = source.list_manager;
                        rows = source.Rows;
                        selected_rows = source.SelectedRows;
@@ -1251,7 +1304,6 @@ namespace System.Windows.Forms
                        CurrentCell = source.current;
                }
 
-               [MonoTODO]
                public void NavigateTo (int rowNumber, string relationName)
                {
                        if (allow_navigation == false)
@@ -1262,7 +1314,7 @@ namespace System.Windows.Forms
                        previous_source.SelectedRows = selected_rows;
                        previous_source.SelectionStart = selection_start;
 
-                       dataSourceStack.Push (previous_source);
+                       data_source_stack.Push (previous_source);
 
                        rows = null;
                        selected_rows = new Hashtable ();
@@ -1336,6 +1388,7 @@ namespace System.Windows.Forms
                protected override void OnEnter (EventArgs e)
                {
                        base.OnEnter (e);
+                       Edit ();
                }
 
                protected virtual void OnFlatModeChanged (EventArgs e)
@@ -1367,20 +1420,24 @@ namespace System.Windows.Forms
                        base.OnHandleDestroyed (e);
                }
 
+               // It seems we have repeated code with ProcessKeyPreview, specifically
+               // the call to ProcessGridKey. In practice it seems this event is *never* fired
+               // since the key events are handled by the current column's textbox. 
+               // We are keeping commented anyway, in case we need to actually call it.
                protected override void OnKeyDown (KeyEventArgs ke)
                {
                        base.OnKeyDown (ke);
                        
-                       if (ProcessGridKey (ke) == true)
+                       /*if (ProcessGridKey (ke) == true)
                                ke.Handled = true;
 
-                       /* TODO: we probably don't need this check,
-                        * since current_cell wouldn't have been set
-                        * to something invalid */
+                       // TODO: we probably don't need this check,
+                       // since current_cell wouldn't have been set
+                       // to something invalid
                        if (CurrentTableStyle.GridColumnStyles.Count > 0) {
                                CurrentTableStyle.GridColumnStyles[current_cell.ColumnNumber].OnKeyDown
                                        (ke, current_cell.RowNumber, current_cell.ColumnNumber);
-                       }
+                       }*/
                }
 
                protected override void OnKeyPress (KeyPressEventArgs kpe)
@@ -1391,24 +1448,17 @@ namespace System.Windows.Forms
                protected override void OnLayout (LayoutEventArgs levent)
                {
                        base.OnLayout (levent);
-                       CalcAreasAndInvalidate ();                      
+                       CalcAreasAndInvalidate ();
                }
 
                protected override void OnLeave (EventArgs e)
                {
                        base.OnLeave (e);
 
-#if false
-                       /* we get an OnLeave call when the
-                        * DataGridTextBox control is focused, so we
-                        * need to ignore that.  If we get an OnLeave
-                        * call when a child control is not receiving
-                        * focus, we need to cancel the current
-                        * edit. */
+                       EndEdit ();
                        if (cursor_in_add_row) {
                                ListManager.CancelCurrentEdit ();
                        }
-#endif
                }
 
                protected override void OnMouseDown (MouseEventArgs e)
@@ -1440,6 +1490,7 @@ namespace System.Windows.Forms
                                DataGridCell new_cell = new DataGridCell (testinfo.Row, testinfo.Column);
 
                                if ((new_cell.Equals (current_cell) == false) || (!is_editing)) {
+                                       ResetSelection ();
                                        CurrentCell = new_cell;
                                        Edit ();
                                } else {
@@ -1451,7 +1502,7 @@ namespace System.Windows.Forms
                        case HitTestType.RowHeader:
                                bool expansion_click = false;
                                if (CurrentTableStyle.HasRelations) {
-                                       if (e.X > rowhdrs_area.X + rowhdrs_area.Width / 2) {
+                                       if (e.X > row_headers_area.X + row_headers_area.Width / 2) {
                                                /* it's in the +/- space */
                                                if (IsExpanded (testinfo.Row))
                                                        Collapse (testinfo.Row);
@@ -1462,23 +1513,20 @@ namespace System.Windows.Forms
                                        }
                                }
 
-                               if (!ctrl_pressed &&
-                                   !shift_pressed &&
-                                   !expansion_click) {
+                               CancelEditing ();
+                               CurrentRow = testinfo.Row;
+
+                               if (!ctrl_pressed && !shift_pressed && !expansion_click) {
                                        ResetSelection (); // Invalidates selected rows
                                }
 
-                               if ((shift_pressed ||
-                                    expansion_click)
-                                   && selection_start != -1) {
+                               if ((shift_pressed || expansion_click) && selection_start != -1) {
                                        ShiftSelection (testinfo.Row);
                                } else { // ctrl_pressed or single item
                                        selection_start = testinfo.Row;
                                        Select (testinfo.Row);
                                }
 
-                               CancelEditing ();
-                               CurrentRow = testinfo.Row;
                                OnRowHeaderClick (EventArgs.Empty);
 
                                break;
@@ -1492,6 +1540,10 @@ namespace System.Windows.Forms
 
                                if (ListManager.List is IBindingList == false)
                                        break;
+
+                               // Don't do any sort if we are empty, as .net does
+                               if (ListManager.Count == 0)
+                                       return;
                        
                                ListSortDirection direction = ListSortDirection.Ascending;
                                PropertyDescriptor prop = CurrentTableStyle.GridColumnStyles[testinfo.Column].PropertyDescriptor;
@@ -1512,13 +1564,17 @@ namespace System.Windows.Forms
                                
                                list.ApplySort (prop, direction);
                                Refresh ();
+                               if (this.is_editing)
+                                       //CurrentTableStyle.GridColumnStyles[CurrentColumn].UpdateUI ();
+                                       this.InvalidateColumn (CurrentTableStyle.GridColumnStyles[CurrentColumn]);
+
                                break;
 
                        case HitTestType.ColumnResize:
                                if (e.Clicks == 2) {
-                                       // double click column resize goes here
-                               }
-                               else {
+                                       EndEdit ();
+                                       ColumnResize (testinfo.Column);
+                               else {
                                        resize_column = testinfo.Column;
                                        column_resize_active = true;
                                        resize_column_x = e.X;
@@ -1530,9 +1586,9 @@ namespace System.Windows.Forms
 
                        case HitTestType.RowResize:
                                if (e.Clicks == 2) {
-                                       // double click row resize goes here
-                               }
-                               else {
+                                       EndEdit ();
+                                       RowResize (testinfo.Row);
+                               else {
                                        resize_row = testinfo.Row;
                                        row_resize_active = true;
                                        resize_row_y = e.Y;
@@ -1605,8 +1661,7 @@ namespace System.Windows.Forms
                                                if (!back_button_mouseover)
                                                        Invalidate (back_button_rect);
                                                back_button_mouseover = true;
-                                       }
-                                       else if (back_button_mouseover) {
+                                       } else if (back_button_mouseover) {
                                                Invalidate (back_button_rect);
                                                back_button_mouseover = false;
                                        }
@@ -1615,8 +1670,7 @@ namespace System.Windows.Forms
                                                if (parent_rows_button_mouseover)
                                                        Invalidate (parent_rows_button_rect);
                                                parent_rows_button_mouseover = true;
-                                       }
-                                       else if (parent_rows_button_mouseover) {
+                                       } else if (parent_rows_button_mouseover) {
                                                Invalidate (parent_rows_button_rect);
                                                parent_rows_button_mouseover = false;
                                        }
@@ -1631,6 +1685,12 @@ namespace System.Windows.Forms
                                                }
                                        }
 
+                                       Cursor = Cursors.Default;
+                                       break;
+                               case HitTestType.RowHeader:
+                                       if (e.Button == MouseButtons.Left)
+                                               ShiftSelection (testinfo.Row);
+
                                        Cursor = Cursors.Default;
                                        break;
                                default:
@@ -1652,8 +1712,7 @@ namespace System.Windows.Forms
                                width_of_all_columns += resize_column_width_delta;
                                Edit ();
                                Invalidate ();
-                       }
-                       else if (row_resize_active) {
+                       } else if (row_resize_active) {
                                row_resize_active = false;
 
                                if (resize_row_height_delta + rows[resize_row].Height < 0)
@@ -1665,16 +1724,14 @@ namespace System.Windows.Forms
 
                                Edit ();
                                CalcAreasAndInvalidate ();
-                       }
-                       else if (back_button_active) {
+                       } else if (back_button_active) {
                                if (back_button_rect.Contains (e.X, e.Y)) {
                                        Invalidate (back_button_rect);
                                        NavigateBack ();
                                        OnBackButtonClicked (this, EventArgs.Empty);
                                }
                                back_button_active = false;
-                       }
-                       else if (parent_rows_button_active) {
+                       } else if (parent_rows_button_active) {
                                if (parent_rows_button_rect.Contains (e.X, e.Y)) {
                                        Invalidate (parent_rows_button_rect);
                                        ParentRowsVisible = !ParentRowsVisible;
@@ -1699,8 +1756,7 @@ namespace System.Windows.Forms
                                        /* left */
                                        pixels = Math.Max (horiz_scrollbar.Minimum,
                                                           horiz_scrollbar.Value - horiz_scrollbar.LargeChange);
-                               }
-                               else {
+                               } else {
                                        /* right */
                                        pixels = Math.Min (horiz_scrollbar.Maximum - horiz_scrollbar.LargeChange + 1,
                                                           horiz_scrollbar.Value + horiz_scrollbar.LargeChange);
@@ -1716,8 +1772,7 @@ namespace System.Windows.Forms
                                        /* up */
                                        pixels = Math.Max (vert_scrollbar.Minimum,
                                                           vert_scrollbar.Value - vert_scrollbar.LargeChange);
-                               }
-                               else {
+                               } else {
                                        /* down */
                                        pixels = Math.Min (vert_scrollbar.Maximum - vert_scrollbar.LargeChange + 1,
                                                           vert_scrollbar.Value + vert_scrollbar.LargeChange);
@@ -1801,34 +1856,34 @@ namespace System.Windows.Forms
                        if (extend_selection) {
                                CancelEditing ();
                                ShiftSelection (CurrentRow);
-                       }
-                       else {
+                       } else {
                                ResetSelection ();
+                               selection_start = CurrentRow;
                        }
                }
 
                protected bool ProcessGridKey (KeyEventArgs ke)
                {
-                       /* if we have no rows, exit immediately.
-                          XXX is this necessary? */
-                       if (RowsCount == 0)
-                               return false;
-
                        bool ctrl_pressed = ((ke.Modifiers & Keys.Control) != 0);
-                       bool alt_pressed = ((ke.Modifiers & Keys.Alt) != 0);
+                       //bool alt_pressed = ((ke.Modifiers & Keys.Alt) != 0);
                        bool shift_pressed = ((ke.Modifiers & Keys.Shift) != 0);
 
                        switch (ke.KeyCode) {
                        case Keys.Escape:
                                if (is_changing)
                                        AbortEditing ();
-                               else
+                               else {
                                        CancelEditing ();
+
+                                       if (cursor_in_add_row && CurrentRow > 0)
+                                               CurrentRow--;
+                               }
+
                                Edit ();
                                return true;
                                
                        case Keys.D0:
-                               if (alt_pressed) {
+                               if (ctrl_pressed) {
                                        if (is_editing)
                                                CurrentTableStyle.GridColumnStyles[CurrentColumn].EnterNullValue ();
                                        return true;
@@ -1846,8 +1901,7 @@ namespace System.Windows.Forms
                                                CurrentColumn --;
                                        else if ((CurrentRow > 0) && (CurrentColumn == 0))
                                                CurrentCell = new DataGridCell (CurrentRow - 1, CurrentTableStyle.GridColumnStyles.Count - 1);
-                               }
-                               else {
+                               } else {
                                        if (CurrentColumn < CurrentTableStyle.GridColumnStyles.Count - 1)
                                                CurrentColumn ++;
                                        else if ((CurrentRow <= RowsCount) && (CurrentColumn == CurrentTableStyle.GridColumnStyles.Count - 1))
@@ -1861,8 +1915,7 @@ namespace System.Windows.Forms
                        case Keys.Right:
                                if (ctrl_pressed) {
                                        CurrentColumn = CurrentTableStyle.GridColumnStyles.Count - 1;
-                               }
-                               else {
+                               } else {
                                        if (CurrentColumn < CurrentTableStyle.GridColumnStyles.Count - 1) {
                                                CurrentColumn ++;
                                        } else if (CurrentRow < RowsCount - 1
@@ -1879,8 +1932,7 @@ namespace System.Windows.Forms
                        case Keys.Left:
                                if (ctrl_pressed) {
                                        CurrentColumn = 0;
-                               }
-                               else {
+                               } else {
                                        if (current_cell.ColumnNumber > 0)
                                                CurrentColumn --;
                                        else if (CurrentRow > 0)
@@ -1956,11 +2008,14 @@ namespace System.Windows.Forms
                                return true;
 
                        case Keys.Delete:
-                               foreach (int row in selected_rows.Keys) {
-                                       ListManager.RemoveAt (row);                                             
+                               if (is_editing)
+                                       return false;
+                               else if (selected_rows.Keys.Count > 0) {
+                                       foreach (int row in selected_rows.Keys)
+                                               ListManager.RemoveAt (row);
+                                       selected_rows.Clear ();
+                                       CalcAreasAndInvalidate ();
                                }
-                               selected_rows.Clear ();
-                               CalcAreasAndInvalidate ();
 
                                return true;
                        }
@@ -1970,10 +2025,17 @@ namespace System.Windows.Forms
 
                protected override bool ProcessKeyPreview (ref Message m)
                {
-                       if ((Msg)m.Msg == Msg.WM_KEYDOWN) {
+                       if ((Msg) m.Msg == Msg.WM_KEYDOWN) {
                                Keys key = (Keys) m.WParam.ToInt32 ();
                                KeyEventArgs ke = new KeyEventArgs (key);
-                               if (ProcessGridKey (ke) == true) {
+                               if (ProcessGridKey (ke))
+                                       return true;
+
+                               // if we receive a key event, make sure that input is actually
+                               // taken into account.
+                               if (!is_editing) {
+                                       Edit ();
+                                       InvalidateRow (current_cell.RowNumber);
                                        return true;
                                }
                        }
@@ -2013,7 +2075,7 @@ namespace System.Windows.Forms
 
                public void ResetHeaderFont ()
                {
-                       grid_style.HeaderFont = default_style.HeaderFont;
+                       grid_style.HeaderFont = null;
                }
 
                public void ResetHeaderForeColor ()
@@ -2058,13 +2120,27 @@ namespace System.Windows.Forms
 
                public void Select (int row)
                {
+                       EndEdit();
+
                        if (selected_rows.Count == 0)
                                selection_start = row;
 
+#if NET_2_0
+                       // UIA Framework: To raise event only when selecting
+                       bool wasSelected = rows [row].IsSelected;
+#endif
+
                        selected_rows[row] = true;
                        rows[row].IsSelected = true;
 
                        InvalidateRow (row);
+
+#if NET_2_0
+                       // UIA Framework:
+                       if (!wasSelected)
+                               OnUIASelectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Add, row));
+#endif
+
                }
 
                public void SetDataBinding (object dataSource, string dataMember)
@@ -2119,12 +2195,12 @@ namespace System.Windows.Forms
 
                protected virtual bool ShouldSerializeParentRowsBackColor ()
                {
-                       return parentrowsback_color != def_parentrowsback_color;
+                       return parent_rows_backcolor != def_parent_rows_backcolor;
                }
 
                protected virtual bool ShouldSerializeParentRowsForeColor ()
                {
-                       return parentrowsback_color != def_parentrowsback_color;
+                       return parent_rows_backcolor != def_parent_rows_backcolor;
                }
 
                protected bool ShouldSerializePreferredRowHeight ()
@@ -2148,9 +2224,20 @@ namespace System.Windows.Forms
 
                public void UnSelect (int row)
                {
+#if NET_2_0
+                       // UIA Framework: To raise event only when unselecting 
+                       bool wasSelected = rows  [row].IsSelected;
+
+#endif
                        rows[row].IsSelected = false;
                        selected_rows.Remove (row);
                        InvalidateRow (row);
+
+#if NET_2_0
+                       // UIA Framework: Raises selection event
+                       if (!wasSelected)
+                               OnUIASelectionChangedEvent (new CollectionChangeEventArgs (CollectionChangeAction.Remove, row));
+#endif
                }
                #endregion      // Public Instance Methods
 
@@ -2233,32 +2320,32 @@ namespace System.Windows.Forms
 
                private void EnsureCellVisibility (DataGridCell cell)
                {
-                       if (cell.ColumnNumber <= first_visiblecolumn ||
-                               cell.ColumnNumber + 1 >= first_visiblecolumn + visiblecolumn_count) {                   
+                       if (cell.ColumnNumber <= first_visible_column ||
+                               cell.ColumnNumber + 1 >= first_visible_column + visible_column_count) {
 
-                               first_visiblecolumn = GetFirstColumnForColumnVisibility (first_visiblecolumn, cell.ColumnNumber);
-                                int pixel = GetColumnStartingPixel (first_visiblecolumn);
+                               first_visible_column = GetFirstColumnForColumnVisibility (first_visible_column, cell.ColumnNumber);
+                               int pixel = GetColumnStartingPixel (first_visible_column);
                                ScrollToColumnInPixels (pixel);
                                horiz_scrollbar.Value = pixel;
                                Update();
                        }
 
-                       if (cell.RowNumber < first_visiblerow ||
-                           cell.RowNumber + 1 >= first_visiblerow + visiblerow_count) {
+                       if (cell.RowNumber < first_visible_row ||
+                           cell.RowNumber + 1 >= first_visible_row + visible_row_count) {
 
-                                if (cell.RowNumber + 1 >= first_visiblerow + visiblerow_count) {
-                                       int old_first_visiblerow = first_visiblerow;
-                                       first_visiblerow = 1 + cell.RowNumber - visiblerow_count;
+                               if (cell.RowNumber + 1 >= first_visible_row + visible_row_count) {
+                                       int old_first_visible_row = first_visible_row;
+                                       first_visible_row = 1 + cell.RowNumber - visible_row_count;
                                        UpdateVisibleRowCount ();
-                                       ScrollToRow (old_first_visiblerow, first_visiblerow);
+                                       ScrollToRow (old_first_visible_row, first_visible_row);
                                } else {
-                                       int old_first_visiblerow = first_visiblerow;
-                                       first_visiblerow = cell.RowNumber;
+                                       int old_first_visible_row = first_visible_row;
+                                       first_visible_row = cell.RowNumber;
                                        UpdateVisibleRowCount ();
-                                       ScrollToRow (old_first_visiblerow, first_visiblerow);
+                                       ScrollToRow (old_first_visible_row, first_visible_row);
                                }
 
-                               vert_scrollbar.Value = first_visiblerow;
+                               vert_scrollbar.Value = first_visible_row;
                        }
                }
 
@@ -2308,15 +2395,15 @@ namespace System.Windows.Forms
                        if (list_manager != null)
                                ConnectListManagerEvents ();
 
-                       BindColumns ();
-
                        if (old_lm != list_manager) {
-                               /* reset first_visiblerow to 0 here before
+                               BindColumns ();
+
+                               /* reset first_visible_row to 0 here before
                                 * doing anything that'll requires us to
                                 * figure out if we need a scrollbar. */
                                vert_scrollbar.Value = 0;
                                horiz_scrollbar.Value = 0;
-                               first_visiblerow = 0;
+                               first_visible_row = 0;
 
                                if (recreate_rows)
                                        RecreateDataGridRows (false);
@@ -2345,10 +2432,24 @@ namespace System.Windows.Forms
                                        new_rows[i].VerticalOffset = new_rows[i-1].VerticalOffset + new_rows[i-1].Height;
                        }
 
+#if NET_2_0
+                       // UIA Framework event: Updates collection list depending on binding
+                       CollectionChangeAction action = CollectionChangeAction.Refresh;
+                       if (rows != null) {
+                               if (new_rows.Length - rows.Length > 0)
+                                       action = CollectionChangeAction.Add;
+                               else
+                                       action = CollectionChangeAction.Remove;
+                       }
+#endif
                        rows = new_rows;
 
                        if (recalc)
                                CalcAreasAndInvalidate ();
+#if NET_2_0
+                       // UIA Framework event: Row added/removed 
+                       OnUIACollectionChangedEvent (new CollectionChangeEventArgs (action, -1));
+#endif 
                }
 
                internal void UpdateRowsFrom (DataGridRelationshipRow row)
@@ -2357,9 +2458,8 @@ namespace System.Windows.Forms
                        if (start_index == -1)
                                return;
 
-                       for (int i = start_index + 1; i < rows.Length; i ++) {
+                       for (int i = start_index + 1; i < rows.Length; i ++)
                                rows[i].VerticalOffset = rows[i-1].VerticalOffset + rows[i-1].Height;
-                       }
 
                        CalcAreasAndInvalidate ();
                }
@@ -2369,25 +2469,27 @@ namespace System.Windows.Forms
                        if (list_manager != null) {
                                string list_name = list_manager.GetListName (null);
                                if (TableStyles[list_name] == null) {
-                                       current_style.GridColumnStyles.Clear ();                        
+                                       // no style exists by the supplied name
+                                       current_style.GridColumnStyles.Clear ();
                                        current_style.CreateColumnsForTable (false);
-                               }
-                               else if (CurrentTableStyle.MappingName != list_name) {
+                               } else if (CurrentTableStyle == grid_style ||
+                                        CurrentTableStyle.MappingName != list_name) {
                                        // If the style has been defined by the user, use it
+                                       // Also, if the user provided style is empty,
+                                       // force a bind for it
                                        CurrentTableStyle = styles_collection[list_name];
+                                       current_style.CreateColumnsForTable (current_style.GridColumnStyles.Count > 0);
+                               } else {
                                        current_style.CreateColumnsForTable (true);
                                }
-                               else {
-                                       current_style.CreateColumnsForTable (true);
-                               }
-                       }
-                       else
+                       } else
                                current_style.CreateColumnsForTable (false);
                }
 
                private void OnListManagerMetaDataChanged (object sender, EventArgs e)
                {
                        BindColumns ();
+                       CalcAreasAndInvalidate ();
                }
 
                private void OnListManagerPositionChanged (object sender, EventArgs e)
@@ -2403,8 +2505,7 @@ namespace System.Windows.Forms
                                ResetSelection ();
                                if (rows == null || RowsCount != rows.Length - (ShowEditRow ? 1 : 0))
                                        RecreateDataGridRows (true);
-                       }
-                       else {
+                       } else {
                                InvalidateRow (e.Index);
                        }
                }
@@ -2415,48 +2516,40 @@ namespace System.Windows.Forms
                                return;
                        
                        string list_name = ListManager.GetListName (null);
-                       switch (e.Action){
-                               case CollectionChangeAction.Add: {
-                                       if (e.Element != null && String.Compare (list_name, ((DataGridTableStyle)e.Element).MappingName, true) == 0) {
-                                               CurrentTableStyle = (DataGridTableStyle)e.Element;
-                                               ((DataGridTableStyle) e.Element).CreateColumnsForTable (false);
-                                       }
-                                       break;
+                       switch (e.Action) {
+                       case CollectionChangeAction.Add:
+                               if (e.Element != null && String.Compare (list_name, ((DataGridTableStyle)e.Element).MappingName, true) == 0) {
+                                       CurrentTableStyle = (DataGridTableStyle)e.Element;
+                                       // force to auto detect columns in case the new style is completely empty
+                                       ((DataGridTableStyle) e.Element).CreateColumnsForTable (CurrentTableStyle.GridColumnStyles.Count > 0);
                                }
-
-                               case CollectionChangeAction.Remove: {
-                                       if (e.Element != null && String.Compare (list_name, ((DataGridTableStyle)e.Element).MappingName, true) == 0) {
-                                               CurrentTableStyle = default_style;                                              
+                               break;
+                       case CollectionChangeAction.Remove:
+                               if (e.Element != null && String.Compare (list_name, ((DataGridTableStyle)e.Element).MappingName, true) == 0) {
+                                       CurrentTableStyle = default_style;
+                                       current_style.GridColumnStyles.Clear ();
+                                       current_style.CreateColumnsForTable (false);
+                               }
+                               break;
+                       case CollectionChangeAction.Refresh:
+                               if (CurrentTableStyle == default_style
+                                       || String.Compare (list_name, CurrentTableStyle.MappingName, true) != 0) {
+                                       DataGridTableStyle style = styles_collection [list_name];
+                                       if (style != null) {
+                                               CurrentTableStyle = style;
+                                               current_style.CreateColumnsForTable (false);
+                                       } else {
+                                               CurrentTableStyle = default_style;
                                                current_style.GridColumnStyles.Clear ();
                                                current_style.CreateColumnsForTable (false);
                                        }
-                                       break;
-                               }       
-
-                               
-                               case CollectionChangeAction.Refresh: {
-                                       if (CurrentTableStyle == default_style
-                                           || String.Compare (list_name, CurrentTableStyle.MappingName, true) != 0) {
-
-                                               DataGridTableStyle style = styles_collection [list_name];
-                                               if (style != null) {
-                                                       CurrentTableStyle = style;
-                                                       current_style.CreateColumnsForTable (false);
-                                               }
-                                               else {
-                                                       CurrentTableStyle = default_style;
-                                                       current_style.GridColumnStyles.Clear ();
-                                                       current_style.CreateColumnsForTable (false);
-                                               }
-                                       }
-
-                                       break;
                                }
-                       }                                               
+                               break;
+                       }
                        CalcAreasAndInvalidate ();
                }
 
-               private void AddNewRow ()
+               internal void AddNewRow ()
                {
                        ListManager.EndCurrentEdit ();
                        ListManager.AddNew ();
@@ -2464,15 +2557,21 @@ namespace System.Windows.Forms
 
                private void Edit ()
                {
-                       if (CurrentTableStyle.GridColumnStyles[current_cell.ColumnNumber].bound == false)
+                       if (CurrentTableStyle.GridColumnStyles.Count == 0)
+                               return;
+
+                       if (!CurrentTableStyle.GridColumnStyles[CurrentColumn].bound)
+                               return;
+
+                       if (ListManager != null && ListManager.Count == 0)
                                return;
 
                        is_editing = true;
                        is_changing = false;
-                       
-                       CurrentTableStyle.GridColumnStyles[current_cell.ColumnNumber].Edit (ListManager,
-                               current_cell.RowNumber, GetCellBounds (current_cell.RowNumber, current_cell.ColumnNumber),
-                               _readonly, "", true);
+
+                       CurrentTableStyle.GridColumnStyles[CurrentColumn].Edit (ListManager,
+                               CurrentRow, GetCellBounds (CurrentRow, CurrentColumn),
+                               _readonly, null, true);
                }
 
                private void EndEdit ()
@@ -2480,12 +2579,11 @@ namespace System.Windows.Forms
                        if (CurrentTableStyle.GridColumnStyles.Count == 0)
                                return;
 
-                       if (CurrentTableStyle.GridColumnStyles[current_cell.ColumnNumber].bound == false)
+                       if (!CurrentTableStyle.GridColumnStyles[current_cell.ColumnNumber].bound)
                                return;
 
                        EndEdit (CurrentTableStyle.GridColumnStyles[current_cell.ColumnNumber],
-                                current_cell.RowNumber,
-                                false);
+                               current_cell.RowNumber, false);
                }
 
                private void ShiftSelection (int index)
@@ -2501,17 +2599,15 @@ namespace System.Windows.Forms
                        if (index >= selection_start) {
                                start = selection_start;
                                end = index;
-                       }
-                       else {
+                       } else {
                                start = index;
                                end = selection_start;
                        }
 
                        if (start == -1) start = 0;
 
-                       for (int idx = start; idx <= end; idx ++) {
+                       for (int idx = start; idx <= end; idx ++)
                                Select (idx);
-                       }
                }
 
                private void ScrollToColumnInPixels (int pixel)
@@ -2525,7 +2621,7 @@ namespace System.Windows.Forms
 
                        Rectangle area = cells_area;
 
-                       if (ColumnHeadersVisible == true) {
+                       if (ColumnHeadersVisible) {
                                area.Y -= ColumnHeadersArea.Height;
                                area.Height += ColumnHeadersArea.Height;
                        }
@@ -2553,8 +2649,7 @@ namespace System.Windows.Forms
                        if (new_row > old_row) { // Scrolldown
                                for (i = old_row; i < new_row; i ++)
                                        pixels -= rows[i].Height;
-                       }
-                       else {
+                       } else {
                                for (i = new_row; i < old_row; i ++)
                                        pixels += rows[i].Height;
                        }
@@ -2575,12 +2670,47 @@ namespace System.Windows.Forms
                        XplatUI.ScrollWindow (Handle, rows_area, 0, pixels, false);
 
                        /* if the row is still */
-                       if (CurrentRow >= first_visiblerow && CurrentRow < first_visiblerow + visiblerow_count)
+                       if (CurrentRow >= first_visible_row && CurrentRow < first_visible_row + visible_row_count)
                                Edit ();
                }
 
-               #endregion Private Instance Methods
 
+               private void ColumnResize (int column) 
+               {
+                       CurrencyManager source = this.ListManager;
+                       DataGridColumnStyle style = CurrentTableStyle.GridColumnStyles[column];
+                       string headerText = style.HeaderText;
+                       using (Graphics g = base.CreateGraphics ()) {
+                               int rows = source.Count;
+                               int width = (int)g.MeasureString (headerText, CurrentTableStyle.HeaderFont).Width + 4;
+
+                               for (int i = 0; i < rows; i++) {
+                                       int rowColWidth = (int)style.GetPreferredSize (g, style.GetColumnValueAtRow (source, i)).Width;
+                                       if (rowColWidth > width)
+                                               width = rowColWidth;
+                               }
+                               if (style.Width != width)
+                                       style.Width = width;
+                       }
+               }
+
+               private void RowResize (int row)
+               {
+                       CurrencyManager source = this.ListManager;
+                       using (Graphics g = base.CreateGraphics ()) {
+                               GridColumnStylesCollection columns = CurrentTableStyle.GridColumnStyles;
+                               int colCount = columns.Count;
+                               //int rowCount = source.Count;
+                               int height = 0;
+                               for (int i = 0; i < colCount; i++) {
+                                       object val = columns[i].GetColumnValueAtRow (source, row);
+                                       height = Math.Max (columns[i].GetPreferredHeight (g, val), height);
+                               }
+                               if (this.DataGridRows[row].Height != height)
+                                       this.DataGridRows[row].Height = height;
+                       }
+               }
+               #endregion Private Instance Methods
 
                #region Events
                static object AllowNavigationChangedEvent = new object ();
@@ -2621,6 +2751,15 @@ namespace System.Windows.Forms
                        remove { base.BackgroundImageChanged -= value; }
                }
 
+#if NET_2_0
+               [Browsable(false)]
+               [EditorBrowsable(EditorBrowsableState.Never)]
+               public new event EventHandler BackgroundImageLayoutChanged {
+                       add { base.BackgroundImageLayoutChanged += value; }
+                       remove { base.BackgroundImageLayoutChanged -= value; }
+               }
+#endif
+
                [Browsable(false)]
                [EditorBrowsable(EditorBrowsableState.Never)]
                public new event EventHandler TextChanged {
@@ -2696,9 +2835,6 @@ namespace System.Windows.Forms
                }
                #endregion      // Events
 
-
-
-
                #region Code originally in DataGridDrawingLogic.cs
 
                #region Local Variables
@@ -2708,17 +2844,16 @@ namespace System.Windows.Forms
                int width_of_all_columns;
 
                internal Rectangle caption_area;
-               internal Rectangle columnhdrs_area;     // Used columns header area
-               internal int columnhdrs_maxwidth;       // Total width (max width) for columns headrs
-               internal Rectangle rowhdrs_area;        // Used Headers rows area
+               internal Rectangle column_headers_area; // Used columns header area
+               internal int column_headers_max_width;  // Total width (max width) for columns headrs
+               internal Rectangle row_headers_area;    // Used Headers rows area
                internal Rectangle cells_area;
                #endregion // Local Variables
 
-
                #region Public Instance Methods
 
                // Calc the max with of all columns
-               int CalcAllColumnsWidth ()
+               private int CalcAllColumnsWidth ()
                {
                        int width = 0;
                        int cnt = CurrentTableStyle.GridColumnStyles.Count;
@@ -2733,18 +2868,20 @@ namespace System.Windows.Forms
                }
 
                // Gets a column from a pixel
-               int FromPixelToColumn (int pixel, out int column_x)
+               private int FromPixelToColumn (int pixel, out int column_x)
                {
                        int width = 0;
                        int cnt = CurrentTableStyle.GridColumnStyles.Count;
                        column_x = 0;
 
                        if (cnt == 0)
-                               return 0;
+                               return -1;
                                
                        if (CurrentTableStyle.CurrentRowHeadersVisible) {
-                               width += rowhdrs_area.X + rowhdrs_area.Width;
-                               column_x += rowhdrs_area.X + rowhdrs_area.Width;
+                               width += row_headers_area.X + row_headers_area.Width;
+                               column_x += row_headers_area.X + row_headers_area.Width;
+                               if (pixel < width)
+                                       return -1;
                        }
 
                        for (int col = 0; col < cnt; col++) {
@@ -2782,14 +2919,14 @@ namespace System.Windows.Forms
                }
                
                // Which column has to be the first visible column to ensure a column visibility
-               int GetFirstColumnForColumnVisibility (int current_first_visiblecolumn, int column)
+               int GetFirstColumnForColumnVisibility (int current_first_visible_column, int column)
                {
                        int new_col = column;
                        int width = 0;
                        
-                       if (column > current_first_visiblecolumn) { // Going forward
-                               for (new_col = column; new_col >= 0; new_col--){
-                                       if (CurrentTableStyle.GridColumnStyles[new_col].bound == false)
+                       if (column > current_first_visible_column) { // Going forward
+                               for (new_col = column; new_col >= 0; new_col--) {
+                                       if (!CurrentTableStyle.GridColumnStyles[new_col].bound)
                                                continue;
                                        width += CurrentTableStyle.GridColumnStyles[new_col].Width;
                                        
@@ -2806,7 +2943,7 @@ namespace System.Windows.Forms
                bool in_calc_grid_areas;
                void CalcGridAreas ()
                {
-                       if (IsHandleCreated == false) // Delay calculations until the handle is created
+                       if (!IsHandleCreated) // Delay calculations until the handle is created
                                return;
 
                        /* make sure we don't happen to end up in this method again */
@@ -2839,7 +2976,7 @@ namespace System.Windows.Forms
 
                        /* use a loop to iteratively calculate whether
                         * we need horiz/vert scrollbars. */
-                       for (int i = 0; i < 3; i ++) {
+                       for (int i = 0; i < 3; i++) {
                                if (needVert)
                                        visible_cells_width = cells_area.Width - vert_scrollbar.Width;
                                if (needHoriz)
@@ -2848,7 +2985,7 @@ namespace System.Windows.Forms
                                UpdateVisibleRowCount ();
 
                                needHoriz = (width_of_all_columns > visible_cells_width);
-                               needVert = (allrows > visiblerow_count);
+                               needVert = (allrows > visible_row_count);
                        }
 
                        int horiz_scrollbar_width = ClientRectangle.Width;
@@ -2869,9 +3006,9 @@ namespace System.Windows.Forms
                                if (ShowParentRows)
                                        parent_rows.Width -= vert_scrollbar.Width;
 
-                               if (!ShowingColumnHeaders) {
-                                       if (columnhdrs_area.X + columnhdrs_area.Width > vert_scrollbar.Location.X) {
-                                               columnhdrs_area.Width -= vert_scrollbar.Width;
+                               if (!ColumnHeadersVisible) {
+                                       if (column_headers_area.X + column_headers_area.Width > vert_scrollbar.Location.X) {
+                                               column_headers_area.Width -= vert_scrollbar.Width;
                                        }
                                }
 
@@ -2880,8 +3017,8 @@ namespace System.Windows.Forms
                        }
 
                        if (needVert) {
-                               if (rowhdrs_area.Y + rowhdrs_area.Height > ClientRectangle.Y + ClientRectangle.Height) {
-                                       rowhdrs_area.Height -= horiz_scrollbar.Height;
+                               if (row_headers_area.Y + row_headers_area.Height > ClientRectangle.Y + ClientRectangle.Height) {
+                                       row_headers_area.Height -= horiz_scrollbar.Height;
                                }
 
                                vert_scrollbar.Size = new Size (vert_scrollbar.Width,
@@ -2890,21 +3027,19 @@ namespace System.Windows.Forms
                                vert_scrollbar.Maximum = vert_scrollbar_maximum;
                                Controls.Add (vert_scrollbar);
                                vert_scrollbar.Visible = true;
-                       }
-                       else {
+                       } else {
                                Controls.Remove (vert_scrollbar);
                                vert_scrollbar.Visible = false;
                        }
 
                        if (needHoriz) {
                                horiz_scrollbar.Size = new Size (horiz_scrollbar_width,
-                                                                horiz_scrollbar.Height);
+                                       horiz_scrollbar.Height);
 
                                horiz_scrollbar.Maximum = horiz_scrollbar_maximum;
                                Controls.Add (horiz_scrollbar);
                                horiz_scrollbar.Visible = true;
-                       }
-                       else {
+                       } else {
                                Controls.Remove (horiz_scrollbar);
                                horiz_scrollbar.Visible = false;
                        }
@@ -2925,15 +3060,14 @@ namespace System.Windows.Forms
                                if (caption_area.Height < back_button_image.Height)
                                        caption_area.Height = back_button_image.Height;
                                caption_area.Height += 2;
-                       }
-                       else
+                       } else
                                caption_area.Height = 0;
                }
 
                void CalcCellsArea ()
                {
-                       cells_area.X = ClientRectangle.X + rowhdrs_area.Width;
-                       cells_area.Y = columnhdrs_area.Y + columnhdrs_area.Height;
+                       cells_area.X = ClientRectangle.X + row_headers_area.Width;
+                       cells_area.Y = column_headers_area.Y + column_headers_area.Height;
                        cells_area.Width = ClientRectangle.X + ClientRectangle.Width - cells_area.X;
                        if (cells_area.Width < 0)
                                cells_area.Width = 0;
@@ -2946,29 +3080,29 @@ namespace System.Windows.Forms
                {
                        int max_width_cols;
 
-                       columnhdrs_area.X = ClientRectangle.X;
-                       columnhdrs_area.Y = parent_rows.Y + parent_rows.Height;
+                       column_headers_area.X = ClientRectangle.X;
+                       column_headers_area.Y = parent_rows.Y + parent_rows.Height;
 
                        // TODO: take into account Scrollbars
-                       columnhdrs_maxwidth = ClientRectangle.X + ClientRectangle.Width - columnhdrs_area.X;
-                       max_width_cols = columnhdrs_maxwidth;
+                       column_headers_max_width = ClientRectangle.X + ClientRectangle.Width - column_headers_area.X;
+                       max_width_cols = column_headers_max_width;
 
                        if (CurrentTableStyle.CurrentRowHeadersVisible)
                                max_width_cols -= RowHeaderWidth;
 
                        if (width_of_all_columns > max_width_cols) {
-                               columnhdrs_area.Width = columnhdrs_maxwidth;
+                               column_headers_area.Width = column_headers_max_width;
                        } else {
-                               columnhdrs_area.Width = width_of_all_columns;
+                               column_headers_area.Width = width_of_all_columns;
 
                                if (CurrentTableStyle.CurrentRowHeadersVisible)
-                                       columnhdrs_area.Width += RowHeaderWidth;
+                                       column_headers_area.Width += RowHeaderWidth;
                        }
 
-                       if (ShowingColumnHeaders)
-                               columnhdrs_area.Height = CurrentTableStyle.HeaderFont.Height + 6;
+                       if (ColumnHeadersVisible)
+                               column_headers_area.Height = CurrentTableStyle.HeaderFont.Height + 6;
                        else
-                               columnhdrs_area.Height = 0;
+                               column_headers_area.Height = 0;
                }
 
                void CalcParentRows ()
@@ -2977,36 +3111,35 @@ namespace System.Windows.Forms
                        parent_rows.Y = caption_area.Y + caption_area.Height;
                        parent_rows.Width = ClientRectangle.Width;
                        if (ShowParentRows)
-                               parent_rows.Height = (CaptionFont.Height + 3) * dataSourceStack.Count;
+                               parent_rows.Height = (CaptionFont.Height + 3) * data_source_stack.Count;
                        else
                                parent_rows.Height = 0;
                }
 
                void CalcParentButtons ()
                {
-                       if (dataSourceStack.Count > 0 && CaptionVisible) {
+                       if (data_source_stack.Count > 0 && CaptionVisible) {
                                back_button_rect = new Rectangle (ClientRectangle.X + ClientRectangle.Width - 2 * (caption_area.Height - 2) - 8,
                                                                  caption_area.Height / 2 - back_button_image.Height / 2,
                                                                  back_button_image.Width, back_button_image.Height);
                                parent_rows_button_rect = new Rectangle (ClientRectangle.X + ClientRectangle.Width - (caption_area.Height - 2) - 4,
                                                                         caption_area.Height / 2 - parent_rows_button_image.Height / 2,
                                                                         parent_rows_button_image.Width, parent_rows_button_image.Height);
-                       }
-                       else {
+                       } else {
                                back_button_rect = parent_rows_button_rect = Rectangle.Empty;
                        }
                }
 
                void CalcRowHeaders ()
                {
-                       rowhdrs_area.X = ClientRectangle.X;
-                       rowhdrs_area.Y = columnhdrs_area.Y + columnhdrs_area.Height;
-                       rowhdrs_area.Height = ClientRectangle.Height + ClientRectangle.Y - rowhdrs_area.Y;
+                       row_headers_area.X = ClientRectangle.X;
+                       row_headers_area.Y = column_headers_area.Y + column_headers_area.Height;
+                       row_headers_area.Height = ClientRectangle.Height + ClientRectangle.Y - row_headers_area.Y;
 
                        if (CurrentTableStyle.CurrentRowHeadersVisible)
-                               rowhdrs_area.Width = RowHeaderWidth;
+                               row_headers_area.Width = RowHeaderWidth;
                        else
-                               rowhdrs_area.Width = 0;
+                               row_headers_area.Width = 0;
                }
 
                int GetVisibleRowCount (int visibleHeight)
@@ -3019,7 +3152,7 @@ namespace System.Windows.Forms
                                rows_height += rows[r].Height;
                        }
 
-                       if (r < rows.Length - 1)
+                       if (r <= rows.Length - 1)
                                r ++;
 
                        return r - FirstVisibleRow;
@@ -3027,40 +3160,41 @@ namespace System.Windows.Forms
 
                void UpdateVisibleColumn ()
                {
-                       if (CurrentTableStyle.GridColumnStyles.Count == 0) {
-                               visiblecolumn_count = 0;
-                               return; 
-                       }
+                       visible_column_count = 0;
                        
-                       int col;
-                       int max_pixel = horiz_pixeloffset + cells_area.Width;
-                       int unused;
-
-                       first_visiblecolumn = FromPixelToColumn (horiz_pixeloffset, out unused);
+                       if (CurrentTableStyle.GridColumnStyles.Count == 0)
+                               return;
 
-                       col = FromPixelToColumn (max_pixel, out unused);
+                       int min_pixel;
+                       int max_pixel;
+                       int max_col;
+                       int unused;
                        
-                       visiblecolumn_count = 1 + col - first_visiblecolumn;
+                       min_pixel = horiz_pixeloffset;
+                       if (CurrentTableStyle.CurrentRowHeadersVisible)
+                               min_pixel += row_headers_area.X + row_headers_area.Width;
+                       max_pixel = min_pixel + cells_area.Width;
+
+                       first_visible_column = FromPixelToColumn (min_pixel, out unused);
+                       max_col = FromPixelToColumn (max_pixel, out unused);
 
-                       visiblecolumn_count = 0;
-                       for (int i = first_visiblecolumn; i <= col; i ++) {
+                       for (int i = first_visible_column; i <= max_col; i ++) {
                                if (CurrentTableStyle.GridColumnStyles[i].bound)
-                                       visiblecolumn_count++;
+                                       visible_column_count++;
                        }
 
-                       if (first_visiblecolumn + visiblecolumn_count < CurrentTableStyle.GridColumnStyles.Count) { 
-                               visiblecolumn_count++; // Partially visible column
+                       if (first_visible_column + visible_column_count < CurrentTableStyle.GridColumnStyles.Count) { 
+                               visible_column_count++; // Partially visible column
                        }
                }
 
                void UpdateVisibleRowCount ()
                {
-                       visiblerow_count = GetVisibleRowCount (cells_area.Height);
+                       visible_row_count = GetVisibleRowCount (cells_area.Height);
 
                        CalcRowHeaders (); // Height depends on num of visible rows
                }
 
-
                void InvalidateCaption ()
                {
                        if (caption_area.IsEmpty)
@@ -3088,10 +3222,10 @@ namespace System.Windows.Forms
                void InvalidateRowHeader (int row)
                {
                        Rectangle rect_rowhdr = new Rectangle ();
-                       rect_rowhdr.X = rowhdrs_area.X;
-                       rect_rowhdr.Width = rowhdrs_area.Width;
+                       rect_rowhdr.X = row_headers_area.X;
+                       rect_rowhdr.Width = row_headers_area.Width;
                        rect_rowhdr.Height = rows[row].Height;
-                       rect_rowhdr.Y = rowhdrs_area.Y + rows[row].VerticalOffset - rows[FirstVisibleRow].VerticalOffset;
+                       rect_rowhdr.Y = row_headers_area.Y + rows[row].VerticalOffset - rows[FirstVisibleRow].VerticalOffset;
                        Invalidate (rect_rowhdr);
                }
 
@@ -3138,7 +3272,6 @@ namespace System.Windows.Forms
                        horiz_scrollbar.LargeChange = cells_area.Width;
                }
 
-
                void SetUpVerticalScrollBar (out int height, out int maximum)
                {
                        int y;
@@ -3152,7 +3285,7 @@ namespace System.Windows.Forms
                        maximum = RowsCount;
                        
                        if (ShowEditRow && RowsCount > 0) {
-                               maximum++;      
+                               maximum++;
                        }
                        
                        vert_scrollbar.LargeChange = VLargeChange;
@@ -3164,7 +3297,7 @@ namespace System.Windows.Forms
                // Returns the ColumnHeaders area excluding the rectangle shared with RowHeaders
                internal Rectangle ColumnHeadersArea {
                        get {
-                               Rectangle columns_area = columnhdrs_area;
+                               Rectangle columns_area = column_headers_area;
 
                                if (CurrentTableStyle.CurrentRowHeadersVisible) {
                                        columns_area.X += RowHeaderWidth;
@@ -3174,12 +3307,8 @@ namespace System.Windows.Forms
                        }
                }
 
-               bool ShowingColumnHeaders {
-                       get { return ColumnHeadersVisible && CurrentTableStyle.GridColumnStyles.Count > 0; }
-               }
-
                internal Rectangle RowHeadersArea {
-                       get { return rowhdrs_area; }
+                       get { return row_headers_area; }
                }
 
                internal Rectangle ParentRowsArea {
@@ -3193,5 +3322,102 @@ namespace System.Windows.Forms
                #endregion Instance Properties
 
                #endregion // Code originally in DataGridDrawingLogic.cs
+
+#if NET_2_0
+               
+               #region UIA Framework: Methods, Properties and Events
+               
+               static object UIACollectionChangedEvent = new object ();
+               static object UIASelectionChangedEvent = new object ();
+               static object UIAColumnHeadersVisibleChangedEvent = new object ();
+               static object UIAGridCellChangedEvent = new object ();
+
+               internal ScrollBar UIAHScrollBar {
+                       get { return horiz_scrollbar; }
+               }
+
+               internal ScrollBar UIAVScrollBar {
+                       get { return vert_scrollbar; }
+               }
+
+               internal DataGridTableStyle UIACurrentTableStyle {
+                       get { return current_style; }
+               }
+
+               internal int UIASelectedRows {
+                       get { return selected_rows.Count; }
+               }
+
+               internal Rectangle UIAColumnHeadersArea {
+                       get { return ColumnHeadersArea; }
+               }
+
+               internal Rectangle UIACaptionArea {
+                       get { return caption_area; }
+               }
+
+               internal Rectangle UIACellsArea {
+                       get { return cells_area; }
+               }
+
+               internal int UIARowHeight {
+                       get { return RowHeight; }
+               }
+
+               internal event CollectionChangeEventHandler UIACollectionChanged {
+                       add { Events.AddHandler (UIACollectionChangedEvent, value); }
+                       remove { Events.RemoveHandler (UIACollectionChangedEvent, value); }
+               }
+
+               internal event CollectionChangeEventHandler UIASelectionChanged {
+                       add { Events.AddHandler (UIASelectionChangedEvent, value); }
+                       remove { Events.RemoveHandler (UIASelectionChangedEvent, value); }
+               }
+
+               internal event EventHandler UIAColumnHeadersVisibleChanged {
+                       add { Events.AddHandler (UIAColumnHeadersVisibleChangedEvent, value); }
+                       remove { Events.RemoveHandler (UIAColumnHeadersVisibleChangedEvent, value); }
+               }
+
+               internal event CollectionChangeEventHandler UIAGridCellChanged {
+                       add { Events.AddHandler (UIAGridCellChangedEvent, value); }
+                       remove { Events.RemoveHandler (UIAGridCellChangedEvent, value); }
+               }
+
+               internal void OnUIACollectionChangedEvent (CollectionChangeEventArgs args)
+               {
+                       CollectionChangeEventHandler eh
+                               = (CollectionChangeEventHandler) Events [UIACollectionChangedEvent];
+                       if (eh != null)
+                               eh (this, args);
+               }
+
+               internal void OnUIASelectionChangedEvent (CollectionChangeEventArgs args)
+               {
+                       CollectionChangeEventHandler eh
+                               = (CollectionChangeEventHandler) Events [UIASelectionChangedEvent];
+                       if (eh != null)
+                               eh (this, args);
+               }
+
+               internal void OnUIAColumnHeadersVisibleChanged ()
+               {
+                       EventHandler eh = (EventHandler) Events [UIAColumnHeadersVisibleChangedEvent];
+                       if (eh != null)
+                               eh (this, EventArgs.Empty);
+               }
+
+               internal void OnUIAGridCellChanged (CollectionChangeEventArgs args)
+               {
+                       CollectionChangeEventHandler eh
+                               = (CollectionChangeEventHandler) Events [UIAGridCellChangedEvent];
+                       if (eh != null)
+                               eh (this, args);
+               }
+
+               #endregion // UIA Framework: Methods, Properties and Events
+
+#endif
+
        }
 }