protected void AssertDataGridViewSelectionModesSame(IDataGridView dataGridView)
        {
            DataGridViewSelectionMode DataGridViewSelectionMode = dataGridView.SelectionMode;
            string DataGridViewSelectionModeToString            = GetUnderlyingDataGridViewSelectionModeToString(dataGridView);

            Assert.AreEqual(DataGridViewSelectionMode.ToString(), DataGridViewSelectionModeToString);
        }
示例#2
0
        // Запись данных из массива (одномерного или двухмерного) в DataGridView
        // (основная реализация, закрытый метод, используется в ArrayToGrid и Array2ToGrid)
        private static void ArrayToGridInner <T>(DataGridView dgv, Array data)
        {
            // выравнивание (если T == int - по правому краю, иначе - по-умолчанию)
            dgv.DefaultCellStyle.Alignment =
                typeof(T) == typeof(int) ? DataGridViewContentAlignment.MiddleRight : dgv.DefaultCellStyle.Alignment;

            int rowCount = data.Rank == 1 ? 1 : data.GetLength(0),
                colCount = data.Rank == 1 ? data.GetLength(0) : data.GetLength(1);

            DataGridViewSelectionMode originalSelectionMode = dgv.SelectionMode;

            dgv.SelectionMode = DataGridViewSelectionMode.CellSelect;
            dgv.RowCount      = rowCount;
            dgv.ColumnCount   = colCount;
            dgv.SelectionMode = originalSelectionMode;

            for (int r = 0; r < rowCount; r++)
            {
                for (int c = 0; c < colCount; c++)
                //dgv[c, r].Value = data.Rank == 1 ? data.GetValue(c) : data.GetValue(r, c);
                //        if (data[r, c] == Game.CellColor.BLUE)
                {
                }
            }
        }
示例#3
0
        void toClear()
        {
            DataGridViewSelectionMode firstmode = dataGridViewByName.SelectionMode;

            dataGridViewByName.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridViewByName.ClearSelection();
            dataGridViewByName.SelectionMode = firstmode;
        }
示例#4
0
        private void InitializeView(DataGridView view, DataGridViewSelectionMode selectionMode)
        {
            foreach (DataGridViewColumn col in view.Columns)
            {
                col.SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            view.SelectionMode = selectionMode;
        }
 ///<summary>
 /// Gets the Habanero <see cref="Base.DataGridViewSelectionMode"/> equivalent to the provided System.Windows.Forms <see cref="DataGridViewSelectionMode"/>.
 ///</summary>
 ///<param name="DataGridViewSelectionMode">A System.Windows.Forms <see cref="DataGridViewSelectionMode"/>.</param>
 ///<returns>The equivalent Habanero <see cref="Base.DataGridViewSelectionMode"/>.</returns>
 public static Base.DataGridViewSelectionMode GetDataGridViewSelectionMode(DataGridViewSelectionMode DataGridViewSelectionMode)
 {
     switch (DataGridViewSelectionMode)
     {
         case DataGridViewSelectionMode.CellSelect: return Base.DataGridViewSelectionMode.CellSelect;
         case DataGridViewSelectionMode.FullRowSelect: return Base.DataGridViewSelectionMode.FullRowSelect;
         case DataGridViewSelectionMode.FullColumnSelect: return Base.DataGridViewSelectionMode.FullColumnSelect;
         case DataGridViewSelectionMode.RowHeaderSelect: return Base.DataGridViewSelectionMode.RowHeaderSelect;
         case DataGridViewSelectionMode.ColumnHeaderSelect: return Base.DataGridViewSelectionMode.ColumnHeaderSelect;
     }
     return (Base.DataGridViewSelectionMode)DataGridViewSelectionMode;
 }
示例#6
0
        /// <summary>
        /// 刷新数据表
        /// </summary>
        /// <param name="dataGridView"></param>
        /// <param name="dt"></param>
        public static void RefreshDataGridViewDataSource(DataGridView dataGridView, DataTable dt)
        {
            DataGridViewSelectionMode selMode = dataGridView.SelectionMode;

            dataGridView.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
            dataGridView.DataSource    = dt;
            for (int i = 0; i < dataGridView.Columns.Count; i++)
            {
                dataGridView.Columns[i].SortMode = DataGridViewColumnSortMode.Programmatic;
            }
            dataGridView.SelectionMode = selMode;
        }
示例#7
0
 static public void SetDefaultStyle(DataGridView _Dgv, bool _AllowAdd = false, bool _AllowDel     = false,
                                    bool _ReadOnly = true, DataGridViewSelectionMode _SelectModel = DataGridViewSelectionMode.FullRowSelect)
 {
     _Dgv.AllowUserToAddRows    = _AllowAdd;
     _Dgv.AllowUserToDeleteRows = _AllowDel;
     _Dgv.AutoGenerateColumns   = false;
     _Dgv.ReadOnly        = _ReadOnly;
     _Dgv.RowHeadersWidth = 15;
     _Dgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter;
     _Dgv.ColumnHeadersHeightSizeMode             = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
     _Dgv.SelectionMode = _SelectModel;
     _Dgv.Columns.Clear();
 }
示例#8
0
        ///<summary>
        /// Gets the Habanero <see cref="Base.DataGridViewSelectionMode"/> equivalent to the provided System.Windows.Forms <see cref="DataGridViewSelectionMode"/>.
        ///</summary>
        ///<param name="DataGridViewSelectionMode">A System.Windows.Forms <see cref="DataGridViewSelectionMode"/>.</param>
        ///<returns>The equivalent Habanero <see cref="Base.DataGridViewSelectionMode"/>.</returns>
        public static Base.DataGridViewSelectionMode GetDataGridViewSelectionMode(DataGridViewSelectionMode DataGridViewSelectionMode)
        {
            switch (DataGridViewSelectionMode)
            {
            case DataGridViewSelectionMode.CellSelect: return(Base.DataGridViewSelectionMode.CellSelect);

            case DataGridViewSelectionMode.FullRowSelect: return(Base.DataGridViewSelectionMode.FullRowSelect);

            case DataGridViewSelectionMode.FullColumnSelect: return(Base.DataGridViewSelectionMode.FullColumnSelect);

            case DataGridViewSelectionMode.RowHeaderSelect: return(Base.DataGridViewSelectionMode.RowHeaderSelect);

            case DataGridViewSelectionMode.ColumnHeaderSelect: return(Base.DataGridViewSelectionMode.ColumnHeaderSelect);
            }
            return((Base.DataGridViewSelectionMode)DataGridViewSelectionMode);
        }
示例#9
0
        public void SetSelectionMode(DataGridViewSelectionMode mode)
        {
            switch (mode)
            {
            case DataGridViewSelectionMode.FullColumnSelect:
                DefaultCellStyle.SelectionBackColor = _selectionColor;
                SelectionMode = mode;
                break;

            default:
                SelectionMode = DataGridViewSelectionMode.CellSelect;
                DefaultCellStyle.SelectionBackColor = Color.White;
                DefaultCellStyle.SelectionForeColor = Color.Black;
                break;
            }
        }
示例#10
0
        public static void WriteListOfMeasurementsToGridOutput(DataGridView dgv, List <ResultOfMeasurement> list)
        {
            DataGridViewSelectionMode originalSelectionMode = dgv.SelectionMode;

            dgv.SelectionMode = DataGridViewSelectionMode.CellSelect;
            dgv.RowCount      = list.Count;
            dgv.ColumnCount   = 2;
            dgv.SelectionMode = originalSelectionMode;

            for (int r = 0; r < list.Count; r++)
            {
                dgv[0, r].Value = list[r].X;
                dgv[1, r].Value = list[r].Result;
            }
            dgv.Columns[0].HeaderText = "X";
            dgv.Columns[1].HeaderText = "Res";
        }
示例#11
0
        public static void ReadXvaluesFromGridView(DataGridView dgv, List <ResultOfMeasurement> list)
        {
            DataGridViewSelectionMode originalSelectionMode = dgv.SelectionMode;

            dgv.SelectionMode = DataGridViewSelectionMode.CellSelect;
            dgv.ColumnCount   = 1;
            dgv.SelectionMode = originalSelectionMode;
            //dgv.RowCount = list.Count;

            for (int i = 0; i < dgv.RowCount; i++)
            {
                if (dgv[0, i].Value != null)
                {
                    list[i].X = Convert.ToInt32(dgv[0, i].Value);
                }
            }
        }
示例#12
0
        /// <summary>
        /// 생성자 함수
        /// </summary>
        public GridView() : base()
        {
            this.AllowUserToAddRows  = false;
            this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            this.BackgroundColor     = System.Drawing.Color.White;
            DataGridViewCellStyle _style = new DataGridViewCellStyle();

            _style.WrapMode = DataGridViewTriState.False;
            //_style.BackColor					= Color.White;	// 이거 없으면 스크롤 할 때, 컬럼 헤더의 글자가 깨져 보임 -> 화면마다 ColumnHeadersDefaultCellStyle의 BackColor를 지정하는 것으로 변경
            this.ColumnHeadersDefaultCellStyle = _style;
            this.ColumnHeadersHeightSizeMode   = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
            this.DelegateProperty = true;
            this.Dock             = DockStyle.Fill;
            this.ReadOnly         = false;
            this.SelectionMode    = DataGridViewSelectionMode.FullRowSelect;

            // 자동컬럼생성
            this.AutoGenerateColumns = false;
        }
        // We want to select a column when the column header is clicked, and a row when the row header is clicked.
        // The table can select _either_ rows or columns, but not both, so we manually change selection mode.
        public void SwitchMode(DataGridViewSelectionMode newMode)
        {
            if (_table.SelectionMode == newMode)
            {
                return;
            }

            // When holding Shift or Ctrl, the user expects to append to the current selection,
            // but changing the mode clears it, so we need to manually preserve it.
            var selectedCells = _table.SelectedCells;

            _table.SelectionMode = newMode;
            if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.LeftCtrl))
            {
                foreach (DataGridViewCell cell in selectedCells)
                {
                    cell.Selected = true;
                }
            }
        }
示例#14
0
        public static void CarriageListToGrid(DataGridView dgv, List <Carriage> data)
        {
            int rowCount = data.Count,
                colCount = 4;

            DataGridViewSelectionMode originalSelectionMode = dgv.SelectionMode;

            dgv.SelectionMode = DataGridViewSelectionMode.CellSelect;
            dgv.RowCount      = rowCount;
            dgv.ColumnCount   = colCount;
            dgv.SelectionMode = originalSelectionMode;

            for (int r = 0; r < rowCount; r++)
            {
                dgv[0, r].Value = data[r].Number;
                dgv[1, r].Value = data[r].PassNum;
                dgv[2, r].Value = data[r].LuggAmount;
                dgv[3, r].Value = data[r].Comfort;
            }
        }
示例#15
0
        protected override void OnCellClick(DataGridViewCellEventArgs e)
        {
            // Selection mode on the grid will change depending on the grid configuration.
            // If there row headers are enabled the behavior will be dynamic:
            // - Full Row Selection: if the selected cell was the row header
            // - Cell Selection: otherwise
            // If there are no row headers the selection mode will remain as configured on the GridView
            DataGridViewSelectionMode newMode = SelectionMode;

            if (RowHeadersVisible)
            {
                if (e.ColumnIndex == -1)
                {
                    newMode = DataGridViewSelectionMode.FullRowSelect;
                }
                else
                {
                    newMode = DataGridViewSelectionMode.CellSelect;
                }
            }

            if (newMode == SelectionMode || e.RowIndex == -1)
            {
                base.OnCellClick(e);
            }
            else
            {
                // Manually handle cell clicks if we have to switch the selection mode or we need a second click.
                SelectionMode = newMode;
                if (newMode == DataGridViewSelectionMode.CellSelect)
                {
                    CurrentCell          = this[e.ColumnIndex, e.RowIndex];
                    CurrentCell.Selected = true;
                }
                else
                {
                    Rows[e.RowIndex].Selected = true;
                }
            }
        }
示例#16
0
        private void dgvHoloday_SelectionChanged(object sender, EventArgs e)
        {
            DataGridViewSelectionMode mode = dgvHoloday.SelectionMode;

            if (isEdit)
            {
                //MessageBox.Show("选择行发生了改变~~");
                //也可以直接通过下面
                updateholiday = this.dgvHoloday.Rows[index].DataBoundItem as MODEL.doc_holidayedit;
                //只有判断同之前的行数据有不一样的值的时候才需要修改
                if (isShouldBeUpdate)
                {
                    if (ho.UpdateHoliday(updateholiday) == 1)
                    {
                        //  MessageBox.Show("ok");
                        isEdit = false; //将修改状态重新置 为false
                        this.dgvHoloday.DataSource = ho.GetAllholiday(dtYear1.Text);
                    }
                    isShouldBeUpdate = false; //修改完这一条记录之后重置是否需要修改的值
                }
            }
        }
示例#17
0
        /// <summary>
        /// 从当前选择行切换到下一行发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvList_SelectionChanged(object sender, EventArgs e)
        {
            DataGridViewSelectionMode mode = dgvList.SelectionMode;

            if (isEdit)
            {
                //MessageBox.Show("选择行发生了改变~~");
                //也可以直接通过下面
                updateperson = this.dgvList.Rows[index].DataBoundItem as MODEL.Person;
                //只有判断同之前的行数据有不一样的值的时候才需要修改
                if (isShouldBeUpdate)
                {
                    if (pm.UpdatePerson(updateperson) == 1)
                    {
                        MessageBox.Show("ok");
                        isEdit = false; //将修改状态重新置 为false
                        this.dgvList.DataSource = pm.GetAllPersonList(false);
                    }
                    isShouldBeUpdate = false; //修改完这一条记录之后重置是否需要修改的值
                }
            }
            //DataGridViewElementStates i= this.dgvList.SelectedRows[0].State;
        }
        public void DataGridViewRowHeaderCellAccessibleObject_DefaultAction_ReturnsExpected(DataGridViewSelectionMode mode, string expected)
        {
            using DataGridView control = new();
            control.SelectionMode      = mode;
            control.Columns.Add("Column 1", "Header text 1");

            var accessibleObject = (DataGridViewRowHeaderCellAccessibleObject)control.Rows[0].HeaderCell.AccessibilityObject;

            Assert.Equal(expected, accessibleObject.DefaultAction);
            Assert.False(control.IsHandleCreated);
        }
 /// <summary>
 /// The select mode.
 /// </summary>
 /// <param name="grid">The data grid view.</param>
 /// <param name="mode">The data grid view selection mode.</param>
 public void SelectMode(DataGridView grid, DataGridViewSelectionMode mode = DataGridViewSelectionMode.FullRowSelect)
 {
     grid.SelectionMode = mode;  // CellSelect, FullColumnSelect, RowHeaderSelect, ColumnHeaderSelect, FullRowSelect
 }
示例#20
0
		public DataGridView ()
		{
			SetStyle (ControlStyles.Opaque, true);
			//SetStyle (ControlStyles.UserMouse, true);
			SetStyle (ControlStyles.OptimizedDoubleBuffer, true);
			
			adjustedTopLeftHeaderBorderStyle = new DataGridViewAdvancedBorderStyle();
			adjustedTopLeftHeaderBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Single;
			advancedCellBorderStyle = new DataGridViewAdvancedBorderStyle();
			advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Single;
			advancedColumnHeadersBorderStyle = new DataGridViewAdvancedBorderStyle();
			advancedColumnHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Single;
			advancedRowHeadersBorderStyle = new DataGridViewAdvancedBorderStyle();
			advancedRowHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Single;
			alternatingRowsDefaultCellStyle = new DataGridViewCellStyle();
			allowUserToAddRows = true;
			allowUserToDeleteRows = true;
			allowUserToOrderColumns = false;
			allowUserToResizeColumns = true;
			allowUserToResizeRows = true;
			autoGenerateColumns = true;
			autoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
			autoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
			backColor = Control.DefaultBackColor;
			backgroundColor = SystemColors.AppWorkspace;
			borderStyle = BorderStyle.FixedSingle;
			cellBorderStyle = DataGridViewCellBorderStyle.Single;
			clipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithAutoHeaderText;
			columnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
			columnHeadersDefaultCellStyle = new DataGridViewCellStyle();
			columnHeadersDefaultCellStyle.BackColor = SystemColors.Control;
			columnHeadersDefaultCellStyle.ForeColor = SystemColors.WindowText;
			columnHeadersDefaultCellStyle.SelectionBackColor = SystemColors.Highlight;
			columnHeadersDefaultCellStyle.SelectionForeColor = SystemColors.HighlightText;
			columnHeadersDefaultCellStyle.Font = this.Font;
			columnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
			columnHeadersDefaultCellStyle.WrapMode = DataGridViewTriState.True;
			columnHeadersHeight = 23;
			columnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
			columnHeadersVisible = true;
			columns = CreateColumnsInstance();
			columns.CollectionChanged += OnColumnCollectionChanged;
			currentCellAddress = new Point (-1, -1);
			dataMember = String.Empty;
			defaultCellStyle = new DataGridViewCellStyle();
			defaultCellStyle.BackColor = SystemColors.Window;
			defaultCellStyle.ForeColor = SystemColors.ControlText;
			defaultCellStyle.SelectionBackColor = SystemColors.Highlight;
			defaultCellStyle.SelectionForeColor = SystemColors.HighlightText;
			defaultCellStyle.Font = this.Font;
			defaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
			defaultCellStyle.WrapMode = DataGridViewTriState.False;
			editMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
			firstDisplayedScrollingColumnHiddenWidth = 0;
			isCurrentCellDirty = false;
			multiSelect = true;
			readOnly = false;
			rowHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
			rowHeadersDefaultCellStyle = (DataGridViewCellStyle) columnHeadersDefaultCellStyle.Clone ();
			rowHeadersVisible = true;
			rowHeadersWidth = 41;
			rowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;
			rows = CreateRowsInstance();
			rowsDefaultCellStyle = new DataGridViewCellStyle();
			selectionMode = DataGridViewSelectionMode.RowHeaderSelect;
			showCellErrors = true;
			showEditingIcon = true;
			scrollBars = ScrollBars.Both;
			userSetCursor = Cursor.Current;
			virtualMode = false;

			horizontalScrollBar = new HScrollBar();
			horizontalScrollBar.Scroll += OnHScrollBarScroll;
			horizontalScrollBar.Visible = false;
			
			verticalScrollBar = new VScrollBar();
			verticalScrollBar.Scroll += OnVScrollBarScroll;
			verticalScrollBar.Visible = false;
			
			Controls.AddRange (new Control[] {horizontalScrollBar, verticalScrollBar});
		}
        public void DataGridViewColumnCollection_Add_ColumnAutomaticSortModeColumnSelectionModeInInitialization_ThrowsInvalidOperationException(DataGridViewSelectionMode selectionMode)
        {
            using var control = new DataGridView
                  {
                      SelectionMode = selectionMode
                  };
            ISupportInitialize           iSupportInitialize = (ISupportInitialize)control;
            DataGridViewColumnCollection collection         = control.Columns;

            using var column = new DataGridViewColumn(new SubDataGridViewCell())
                  {
                      SortMode = DataGridViewColumnSortMode.Automatic
                  };
            iSupportInitialize.BeginInit();
            collection.Add(column);

            // End init.
            Assert.Throws <InvalidOperationException>(() => iSupportInitialize.EndInit());
            Assert.Equal(DataGridViewSelectionMode.RowHeaderSelect, control.SelectionMode);
        }
        public void DataGridViewColumnCollection_Add_ColumnAutomaticSortModeColumnSelectionMode_ThrowsInvalidOperationException(DataGridViewSelectionMode selectionMode)
        {
            using var control = new DataGridView
                  {
                      SelectionMode = selectionMode
                  };
            var collection = new DataGridViewColumnCollection(control);

            using var column = new DataGridViewColumn(new SubDataGridViewCell())
                  {
                      SortMode = DataGridViewColumnSortMode.Automatic
                  };
            Assert.Throws <InvalidOperationException>(() => collection.Add(column));
        }
        public void DataGridViewColumnCollection_Add_CustomColumnSortModeAndSelectionMode_Success(DataGridViewSelectionMode selectionMode, DataGridViewColumnSortMode sortMode)
        {
            using var control = new DataGridView
                  {
                      SelectionMode = selectionMode
                  };
            DataGridViewColumnCollection collection = control.Columns;

            using var column1 = new DataGridViewColumn(new SubDataGridViewCell())
                  {
                      SortMode = sortMode
                  };
            using var column2 = new DataGridViewColumn(new SubDataGridViewCell())
                  {
                      SortMode = sortMode
                  };

            // Add one.
            collection.Add(column1);
            Assert.Equal(new DataGridViewColumn[] { column1 }, collection.Cast <DataGridViewColumn>());
            Assert.Same(control, column1.DataGridView);
            Assert.Equal(0, column1.Index);
            Assert.Equal(0, column1.DisplayIndex);
            Assert.False(control.IsHandleCreated);

            // Add another.
            collection.Add(column2);
            Assert.Equal(new DataGridViewColumn[] { column1, column2 }, collection.Cast <DataGridViewColumn>());
            Assert.Same(control, column1.DataGridView);
            Assert.Equal(0, column1.Index);
            Assert.Equal(0, column1.DisplayIndex);
            Assert.Same(control, column2.DataGridView);
            Assert.Equal(1, column2.Index);
            Assert.Equal(1, column2.DisplayIndex);
            Assert.False(control.IsHandleCreated);
        }
示例#24
0
        public static DataGridView GetDataGridView(DataGridViewSelectionMode selectionMode, DataGridViewAutoSizeRowsMode rowsSizeMode)
        {
            DataGridView grid = new DataGridView();

            grid.AllowUserToOrderColumns     = true;
            grid.AllowUserToResizeRows       = true;
            grid.AutoSizeRowsMode            = rowsSizeMode;
            grid.AllowUserToDeleteRows       = false;
            grid.AllowUserToAddRows          = false;
            grid.RowHeadersVisible           = false;
            grid.SelectionMode               = selectionMode;
            grid.MultiSelect                 = false;
            grid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            grid.ScrollBars      = ScrollBars.None;
            grid.BackColor       = Color.FromArgb(21, 26, 30);
            grid.BackgroundColor = Color.FromArgb(21, 26, 30);


            grid.GridColor = Color.FromArgb(17, 18, 23);
            grid.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            grid.BorderStyle = BorderStyle.None;
            DataGridViewCellStyle style = new DataGridViewCellStyle();

            style.Alignment          = DataGridViewContentAlignment.TopLeft;
            style.WrapMode           = DataGridViewTriState.True;
            style.BackColor          = Color.FromArgb(21, 26, 30);
            style.SelectionBackColor = Color.FromArgb(17, 18, 23);
            style.ForeColor          = Color.FromArgb(154, 156, 158);



            grid.DefaultCellStyle = style;
            grid.ColumnHeadersDefaultCellStyle = style;

            grid.MouseHover += delegate(object sender, EventArgs args)
            {
                grid.Focus();
            };

            grid.MouseLeave += delegate(object sender, EventArgs args)
            {
                grid.EndEdit();
            };

            grid.MouseWheel += delegate(object sender, MouseEventArgs args)
            {
                if (grid.SelectedCells.Count == 0)
                {
                    return;
                }
                int rowInd = grid.SelectedCells[0].RowIndex;
                if (args.Delta < 0)
                {
                    rowInd++;
                }
                else if (args.Delta > 0)
                {
                    rowInd--;
                }

                if (rowInd < 0)
                {
                    rowInd = 0;
                }

                if (rowInd >= grid.Rows.Count)
                {
                    rowInd = grid.Rows.Count - 1;
                }

                grid.Rows[rowInd].Selected = true;
                grid.Rows[rowInd].Cells[grid.SelectedCells[0].ColumnIndex].Selected = true;

                if (grid.FirstDisplayedScrollingRowIndex > rowInd)
                {
                    grid.FirstDisplayedScrollingRowIndex = rowInd;
                }
            };



            return(grid);
        }
 public DataGridView()
 {
     base.SetStyle(ControlStyles.UserMouse | ControlStyles.Opaque | ControlStyles.UserPaint, true);
     base.SetStyle(ControlStyles.SupportsTransparentBackColor, false);
     base.SetState2(0x800, true);
     this.dataGridViewState1 = new BitVector32(0);
     this.dataGridViewState2 = new BitVector32(0);
     this.dataGridViewOper = new BitVector32(0);
     this.dataGridViewState1[0x80001b] = true;
     this.dataGridViewState2[0x60003e7] = true;
     this.displayedBandsInfo = new DisplayedBandsData();
     this.lstRows = new ArrayList();
     this.converters = new Hashtable(8);
     this.pens = new Hashtable(8);
     this.brushes = new Hashtable(10);
     this.gridPen = new Pen(DefaultGridColor);
     this.selectedBandIndexes = new DataGridViewIntLinkedList();
     this.individualSelectedCells = new DataGridViewCellLinkedList();
     this.individualReadOnlyCells = new DataGridViewCellLinkedList();
     this.advancedCellBorderStyle = new DataGridViewAdvancedBorderStyle(this, DataGridViewAdvancedCellBorderStyle.OutsetDouble, DataGridViewAdvancedCellBorderStyle.OutsetPartial, DataGridViewAdvancedCellBorderStyle.InsetDouble);
     this.advancedRowHeadersBorderStyle = new DataGridViewAdvancedBorderStyle(this);
     this.advancedColumnHeadersBorderStyle = new DataGridViewAdvancedBorderStyle(this);
     this.advancedCellBorderStyle.All = DataGridViewAdvancedCellBorderStyle.Single;
     this.advancedRowHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.OutsetPartial;
     this.advancedColumnHeadersBorderStyle.All = DataGridViewAdvancedCellBorderStyle.OutsetPartial;
     this.borderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
     this.dataGridViewState1[0x80] = true;
     this.selectionMode = DataGridViewSelectionMode.RowHeaderSelect;
     this.editMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
     this.autoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
     this.autoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
     this.columnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
     this.rowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;
     this.clipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithAutoHeaderText;
     this.layout = new LayoutData();
     this.layout.TopLeftHeader = Rectangle.Empty;
     this.layout.ColumnHeaders = Rectangle.Empty;
     this.layout.RowHeaders = Rectangle.Empty;
     this.layout.ColumnHeadersVisible = true;
     this.layout.RowHeadersVisible = true;
     this.layout.ClientRectangle = base.ClientRectangle;
     this.scrollBars = System.Windows.Forms.ScrollBars.Both;
     this.horizScrollBar.RightToLeft = RightToLeft.Inherit;
     this.horizScrollBar.AccessibleName = System.Windows.Forms.SR.GetString("DataGridView_AccHorizontalScrollBarAccName");
     this.horizScrollBar.Top = base.ClientRectangle.Height - this.horizScrollBar.Height;
     this.horizScrollBar.Left = 0;
     this.horizScrollBar.Visible = false;
     this.horizScrollBar.Scroll += new ScrollEventHandler(this.DataGridViewHScrolled);
     base.Controls.Add(this.horizScrollBar);
     this.vertScrollBar.Top = 0;
     this.vertScrollBar.AccessibleName = System.Windows.Forms.SR.GetString("DataGridView_AccVerticalScrollBarAccName");
     this.vertScrollBar.Left = base.ClientRectangle.Width - this.vertScrollBar.Width;
     this.vertScrollBar.Visible = false;
     this.vertScrollBar.Scroll += new ScrollEventHandler(this.DataGridViewVScrolled);
     base.Controls.Add(this.vertScrollBar);
     this.ptCurrentCell = new Point(-1, -1);
     this.ptAnchorCell = new Point(-1, -1);
     this.ptMouseDownCell = new Point(-2, -2);
     this.ptMouseEnteredCell = new Point(-2, -2);
     this.ptToolTipCell = new Point(-1, -1);
     this.ptMouseDownGridCoord = new Point(-1, -1);
     this.sortOrder = System.Windows.Forms.SortOrder.None;
     this.lastMouseClickInfo.timeStamp = 0L;
     this.WireScrollBarsEvents();
     base.PerformLayout();
     this.toolTipControl = new DataGridViewToolTip(this);
     base.Invalidate();
 }
        /// <summary>Paints the current <see cref="T:System.Windows.Forms.DataGridViewColumnHeaderCell" />.</summary>
        /// <param name="graphics">The <see cref="T:System.Drawing.Graphics" /> used to paint the cell.</param>
        /// <param name="clipBounds">A <see cref="T:System.Drawing.Rectangle" /> that represents the area of the <see cref="T:System.Windows.Forms.DataGridView" /> that needs to be repainted.</param>
        /// <param name="cellBounds">A <see cref="T:System.Drawing.Rectangle" /> that contains the bounds of the cell that is being painted.</param>
        /// <param name="rowIndex">The row index of the cell that is being painted.</param>
        /// <param name="dataGridViewElementState">A bitwise combination of <see cref="T:System.Windows.Forms.DataGridViewElementStates" /> values that specifies the state of the cell.</param>
        /// <param name="value">The data of the cell that is being painted.</param>
        /// <param name="formattedValue">The formatted data of the cell that is being painted.</param>
        /// <param name="errorText">An error message that is associated with the cell.</param>
        /// <param name="cellStyle">A <see cref="T:System.Windows.Forms.DataGridViewCellStyle" /> that contains formatting and style information about the cell.</param>
        /// <param name="advancedBorderStyle">A <see cref="T:System.Windows.Forms.DataGridViewAdvancedBorderStyle" /> that contains border styles for the cell that is being painted.</param>
        /// <param name="paintParts">A bitwise combination of the <see cref="T:System.Windows.Forms.DataGridViewPaintParts" /> values that specifies which parts of the cell need to be painted.</param>
        protected override void Paint(
            Graphics graphics,
            Rectangle clipBounds,
            Rectangle cellBounds,
            int rowIndex,
            DataGridViewElementStates dataGridViewElementState,
            object value,
            object formattedValue,
            string errorText,
            DataGridViewCellStyle cellStyle,
            DataGridViewAdvancedBorderStyle advancedBorderStyle,
            DataGridViewPaintParts paintParts)
        {
            void CallBase(bool disableReflection = false)
            {
                if (disableReflection)
                {
                    _reflectionSupported = false;
                }
                base.Paint(
                    graphics,
                    clipBounds,
                    cellBounds,
                    rowIndex,
                    dataGridViewElementState,
                    value,
                    formattedValue,
                    errorText,
                    cellStyle,
                    advancedBorderStyle,
                    paintParts);
            }

            // Hack to force selected column headers NOT to be highlighted. We're in full-row select mode, so
            // highlighting makes no sense and is visually distracting. The DataGridView code is LUDICROUSLY
            // resilient against any attempt to make it stop the highlighting. It has an IsHighlighted() method
            // that it checks, which checks a bunch of properties (no fields directly!) and returns true in our
            // case and thus highlights the column header. One of the things it checks is "Accessibility
            // improvements level 2". We could turn those off with an app config XML property or whatever (can't
            // do it at runtime, of course!), but then that would turn off a bunch of OTHER accessibility stuff
            // that we want to leave on because we don't want to screw people over who may need them just so we
            // can turn off an irrelevant thing that's nothing to do with accessibility (it would be if we WEREN'T
            // full-row select, but as I just said...!)
            // So, instead, we just toggle the underlying field of one of the properties it checks (SelectionMode)
            // while we paint. Thus we force the accursed thing to not paint itself blue. FINALLY.
            // NOTE: In dark mode we don't have to do this because we're already custom drawing the headers then.
            if (rowIndex == -1 && !DarkModeEnabled && _reflectionSupported != false)
            {
                // Do this here because DataGridView will still be null in the ctor. We only do it once app-wide
                // anyway (static) so it's fine.
                if (_reflectionSupported == null)
                {
                    try
                    {
                        selectionModeField = typeof(DataGridView).GetField(WinFormsReflection.DGV_SelectionModeBackingFieldName, _bfAll);
                        if (selectionModeField == null ||
                            selectionModeField.GetValue(DataGridView) is not DataGridViewSelectionMode)
                        {
                            CallBase(disableReflection: true);
                            return;
                        }
                        else
                        {
                            _reflectionSupported = true;
                        }
                    }
                    catch
                    {
                        CallBase(disableReflection: true);
                        return;
                    }
                }

                if (selectionModeField == null)
                {
                    CallBase(disableReflection: true);
                    return;
                }

                DataGridViewSelectionMode oldSelectionMode;
                DataGridViewSelectionMode oldSelectionModeProperty = DataGridView.SelectionMode;
                try
                {
                    oldSelectionMode = (DataGridViewSelectionMode)selectionModeField.GetValue(DataGridView);
                    selectionModeField.SetValue(DataGridView, DataGridViewSelectionMode.CellSelect);
                }
                catch
                {
                    // Force correct selection mode back in this case, because our temp set could have failed
                    DataGridView.SelectionMode = oldSelectionModeProperty;
                    CallBase(disableReflection: true);
                    return;
                }

                try
                {
                    CallBase();
                }
                finally
                {
                    try
                    {
                        selectionModeField.SetValue(DataGridView, oldSelectionMode);
                    }
                    catch
                    {
                        // Ditto
                        DataGridView.SelectionMode = oldSelectionModeProperty;
                        _reflectionSupported       = false;
                    }
                }
            }
            else
            {
                CallBase();
            }
        }
示例#27
0
 /****************************************************************
 ** 函 数 名:InitDataGridView
 ** 功能描述:数据网格初始化
 ** 输入参数:dgvTarget 控件型 <目标数据网格>
 ** 输出参数:无
 ** 返 回 值:无
 ** 创 建 人:陶志强
 ** 日    期:2012-3-17
 ** 修 改 人:
 ** 日    期:
 ****************************************************************/
 public static void InitDataGridView(bool ReadOnly, bool AllowUserToAddRows, bool RowHeadersVisible, bool ColumnHeadersVisible, bool MultiSelect, bool AllowUserToResizeRows, bool AllowUserToResizeColumns, DataGridViewSelectionMode SelectionMode, DataGridView dgvTarget)
 {
     dgvTarget.ReadOnly                 = ReadOnly;
     dgvTarget.AllowUserToAddRows       = AllowUserToAddRows;
     dgvTarget.RowHeadersVisible        = RowHeadersVisible;
     dgvTarget.ColumnHeadersVisible     = ColumnHeadersVisible;
     dgvTarget.SelectionMode            = SelectionMode;
     dgvTarget.MultiSelect              = MultiSelect;
     dgvTarget.AllowUserToResizeRows    = AllowUserToResizeRows;
     dgvTarget.AllowUserToResizeColumns = AllowUserToResizeColumns;
     // dgvTarget.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
 }
示例#28
0
 static string XmlFromControlSelectionModeProperty(DataGridViewSelectionMode SelectionMode)
 {
     return XmlFromTagValue(ModUiTags.SelectionMode, SelectionMode);
 }
示例#29
0
 public void AjustaSelecaoDeLinha(DataGridViewSelectionMode tipoDeSelecao)
 {
     DataGrideView.SelectionMode = tipoDeSelecao;
 }
        public void DataGridViewRowHeaderCellAccessibleObject_DoDefaultAction_DoesNothing_IfHandleIsNotCreated(DataGridViewSelectionMode mode)
        {
            using DataGridView control = new();
            control.SelectionMode      = mode;
            control.Columns.Add("Column 1", "Header text 1");
            DataGridViewRowHeaderCell cell = control.Rows[0].HeaderCell;

            Assert.False(cell.OwningRow.Selected);

            cell.AccessibilityObject.DoDefaultAction();

            Assert.False(cell.OwningRow.Selected);
            Assert.False(control.IsHandleCreated);
        }
#pragma warning restore 0414
#endif
        /// <include file='doc\DataGridView.uex' path='docs/doc[@for="DataGridView.DataGridView"]/*' />
        /// <devdoc>
        /// <para>Initializes a new instance of the <see cref='System.Windows.Forms.DataGridView'/> class.</para>
        /// </devdoc>
        public DataGridView()
        {
            SetStyle(ControlStyles.UserPaint | 
                     ControlStyles.Opaque | 
                     ControlStyles.UserMouse, true);
            
            SetStyle(ControlStyles.SupportsTransparentBackColor, false);

            // this class overrides GetPreferredSizeCore, let Control automatically cache the result
            SetState2(STATE2_USEPREFERREDSIZECACHE, true);  

            this.dataGridViewState1 = new System.Collections.Specialized.BitVector32(0x00000000);
            this.dataGridViewState2 = new System.Collections.Specialized.BitVector32(0x00000000);
            this.dataGridViewOper   = new System.Collections.Specialized.BitVector32(0x00000000);

            this.dataGridViewState1[  DATAGRIDVIEWSTATE1_columnHeadersVisible 
                                    | DATAGRIDVIEWSTATE1_rowHeadersVisible 
                                    | DATAGRIDVIEWSTATE1_autoGenerateColumns
                                    | DATAGRIDVIEWSTATE1_allowUserToAddRows
                                    | DATAGRIDVIEWSTATE1_allowUserToDeleteRows ] = true;



            this.dataGridViewState2[  DATAGRIDVIEWSTATE2_showEditingIcon
                                    | DATAGRIDVIEWSTATE2_enableHeadersVisualStyles
                                    | DATAGRIDVIEWSTATE2_mouseEnterExpected
                                    | DATAGRIDVIEWSTATE2_allowUserToResizeColumns
                                    | DATAGRIDVIEWSTATE2_allowUserToResizeRows
                                    | DATAGRIDVIEWSTATE2_showCellToolTips
                                    | DATAGRIDVIEWSTATE2_showCellErrors
                                    | DATAGRIDVIEWSTATE2_showRowErrors
                                    | DATAGRIDVIEWSTATE2_allowHorizontalScrollbar
                                    | DATAGRIDVIEWSTATE2_usedFillWeightsDirty ] = true;


            this.displayedBandsInfo = new DisplayedBandsData();
            this.lstRows = new ArrayList();

            this.converters = new Hashtable(8);
            this.pens = new Hashtable(8);
            this.brushes = new Hashtable(10);
            this.gridPen = new Pen(DefaultGridColor);

            this.selectedBandIndexes = new DataGridViewIntLinkedList();
            this.individualSelectedCells = new DataGridViewCellLinkedList();
            this.individualReadOnlyCells = new DataGridViewCellLinkedList();

            this.advancedCellBorderStyle = new DataGridViewAdvancedBorderStyle(this, 
                DataGridViewAdvancedCellBorderStyle.OutsetDouble, 
                DataGridViewAdvancedCellBorderStyle.OutsetPartial, 
                DataGridViewAdvancedCellBorderStyle.InsetDouble);
            this.advancedRowHeadersBorderStyle = new DataGridViewAdvancedBorderStyle(this);
            this.advancedColumnHeadersBorderStyle = new DataGridViewAdvancedBorderStyle(this);
            this.advancedCellBorderStyle.All = defaultAdvancedCellBorderStyle;
            this.advancedRowHeadersBorderStyle.All = defaultAdvancedRowHeadersBorderStyle;
            this.advancedColumnHeadersBorderStyle.All = defaultAdvancedColumnHeadersBorderStyle;
            this.borderStyle = defaultBorderStyle;
            this.dataGridViewState1[DATAGRIDVIEWSTATE1_multiSelect] = true;
            this.selectionMode = defaultSelectionMode;
            this.editMode = defaultEditMode;
            this.autoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
            this.autoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
            this.columnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
            this.rowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing;

            this.clipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithAutoHeaderText;

            this.layout = new LayoutData();
            this.layout.TopLeftHeader        = Rectangle.Empty;
            this.layout.ColumnHeaders        = Rectangle.Empty;
            this.layout.RowHeaders           = Rectangle.Empty;
            this.layout.ColumnHeadersVisible = true;
            this.layout.RowHeadersVisible    = true;
            this.layout.ClientRectangle      = this.ClientRectangle;

            this.scrollBars = ScrollBars.Both;

            this.horizScrollBar.RightToLeft = RightToLeft.Inherit;
            this.horizScrollBar.AccessibleName = SR.GetString(SR.DataGridView_AccHorizontalScrollBarAccName);
            this.horizScrollBar.Top = this.ClientRectangle.Height - horizScrollBar.Height;
            this.horizScrollBar.Left = 0;
            this.horizScrollBar.Visible = false;
            this.horizScrollBar.Scroll += new ScrollEventHandler(DataGridViewHScrolled);
            this.Controls.Add(this.horizScrollBar);

            this.vertScrollBar.Top = 0;
            this.vertScrollBar.AccessibleName = SR.GetString(SR.DataGridView_AccVerticalScrollBarAccName);
            this.vertScrollBar.Left = this.ClientRectangle.Width - vertScrollBar.Width;
            this.vertScrollBar.Visible = false;
            this.vertScrollBar.Scroll += new ScrollEventHandler(DataGridViewVScrolled);
            this.Controls.Add(this.vertScrollBar);

            this.ptCurrentCell = new Point(-1, -1);
            this.ptAnchorCell = new Point(-1, -1);
            this.ptMouseDownCell = new Point(-2, -2);
            this.ptMouseEnteredCell = new Point(-2, -2);
            this.ptToolTipCell = new Point(-1, -1);
            this.ptMouseDownGridCoord = new Point(-1, -1);

            this.sortOrder = SortOrder.None;

            this.lastMouseClickInfo.timeStamp = 0;

            WireScrollBarsEvents();
            PerformLayout();

            this.toolTipControl = new DataGridViewToolTip(this);
            
            Invalidate();
        }
示例#32
0
        public static DataGridView GetDataGridView(DataGridViewSelectionMode selectionMode, DataGridViewAutoSizeRowsMode rowsSizeMode, bool createSaveMenu = false)
        {
            DataGridView grid = new DataGridView();

            grid.AllowUserToOrderColumns     = true;
            grid.AllowUserToResizeRows       = true;
            grid.AutoSizeRowsMode            = rowsSizeMode;
            grid.AllowUserToDeleteRows       = false;
            grid.AllowUserToAddRows          = false;
            grid.RowHeadersVisible           = false;
            grid.SelectionMode               = selectionMode;
            grid.MultiSelect                 = false;
            grid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            grid.ScrollBars      = ScrollBars.None;
            grid.BackColor       = Color.FromArgb(21, 26, 30);
            grid.BackgroundColor = Color.FromArgb(21, 26, 30);

            grid.GridColor = Color.FromArgb(17, 18, 23);
            grid.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            grid.BorderStyle = BorderStyle.None;
            DataGridViewCellStyle style = new DataGridViewCellStyle();

            style.Alignment          = DataGridViewContentAlignment.TopLeft;
            style.WrapMode           = DataGridViewTriState.True;
            style.BackColor          = Color.FromArgb(21, 26, 30);
            style.SelectionBackColor = Color.FromArgb(17, 18, 23);
            style.ForeColor          = Color.FromArgb(154, 156, 158);

            grid.DefaultCellStyle = style;
            grid.ColumnHeadersDefaultCellStyle = style;

            grid.MouseHover += delegate(object sender, EventArgs args)
            {
                grid.Focus();
            };

            grid.MouseLeave += delegate(object sender, EventArgs args)
            {
                grid.EndEdit();
            };

            grid.MouseWheel += delegate(object sender, MouseEventArgs args)
            {
                if (grid.SelectedCells.Count == 0)
                {
                    return;
                }
                int rowInd = grid.SelectedCells[0].RowIndex;
                if (args.Delta < 0)
                {
                    rowInd++;
                }
                else if (args.Delta > 0)
                {
                    rowInd--;
                }

                if (rowInd < 0)
                {
                    rowInd = 0;
                }

                if (rowInd >= grid.Rows.Count)
                {
                    rowInd = grid.Rows.Count - 1;
                }

                grid.Rows[rowInd].Selected = true;
                grid.Rows[rowInd].Cells[grid.SelectedCells[0].ColumnIndex].Selected = true;

                if (grid.FirstDisplayedScrollingRowIndex > rowInd)
                {
                    grid.FirstDisplayedScrollingRowIndex = rowInd;
                }
            };

            if (createSaveMenu)
            {
                List <MenuItem> items = new List <MenuItem>();

                items.Add(new MenuItem("Save table in file"));

                items[items.Count - 1].Click += delegate(Object sender, EventArgs e)
                {
                    if (grid.Rows.Count == 0)
                    {
                        return;
                    }

                    try
                    {
                        SaveFileDialog myDialog = new SaveFileDialog();
                        myDialog.Filter = "*.txt|";
                        myDialog.ShowDialog();

                        if (string.IsNullOrEmpty(myDialog.FileName))
                        {
                            MessageBox.Show(OsLocalization.Journal.Message1);
                            return;
                        }

                        string fileName = myDialog.FileName;
                        if (fileName.Split('.').Length == 1)
                        {
                            fileName = fileName + ".txt";
                        }

                        string saveStr = "";

                        for (int i = 0; i < grid.Columns.Count; i++)
                        {
                            saveStr += grid.Columns[i].HeaderText + ",";
                        }

                        saveStr += "\r\n";

                        for (int i = 0; i < grid.Rows.Count; i++)
                        {
                            saveStr += grid.Rows[i].ToFormatString() + "\r\n";
                        }


                        StreamWriter writer = new StreamWriter(fileName);
                        writer.Write(saveStr);
                        writer.Close();
                    }
                    catch (Exception error)
                    {
                        MessageBox.Show(error.ToString());
                    }
                };

                ContextMenu menu = new ContextMenu(items.ToArray());
                grid.ContextMenu = menu;

                grid.Click += delegate(Object sender, EventArgs e)
                {
                    MouseEventArgs mouse = (MouseEventArgs)e;
                    if (mouse.Button != MouseButtons.Right)
                    {
                        return;
                    }

                    grid.ContextMenu = menu;
                    grid.ContextMenu.Show(grid, new Point(mouse.X, mouse.Y));
                };
            }

            return(grid);
        }
        public void DataGridViewRowHeaderCellAccessibleObject_DoDefaultAction_WorksExpected(DataGridViewSelectionMode mode, bool expected)
        {
            using DataGridView control = new();
            control.SelectionMode      = mode;
            control.Columns.Add("Column 1", "Header text 1");
            DataGridViewRowHeaderCell cell = control.Rows[0].HeaderCell;

            control.CreateControl();

            Assert.False(cell.OwningRow.Selected);

            cell.AccessibilityObject.DoDefaultAction();

            Assert.Equal(expected, cell.OwningRow.Selected);
            Assert.True(control.IsHandleCreated);
        }