首页 > 代码库 > DataGridView

DataGridView

一、实现CheckBox列

  1.1 增加CheckBox列:

  在DataGridView中增加CheckBox列:

  技术分享注意:设置ColumnType类型和设置FalseValue为0,TrueValue为1.这两个属性是设置CheckBox打钩和不打勾的Value值。

  然后在代码中赋予初始值:

  技术分享

  1.2 在DataGridView的CellContentClick事件进行处理:

  该事件是在点击CheckBox之后CheckBox的值更改之前触发,可以使用DataGridViewCellEventArgs类型的参数判断所在点击所在的单元格。

  如果要对CheckBox的点击事件进行取消,可以调用DataGridView的CancelEdit()方法取消点击事件。

二、动态添加列

  1.1 在代码中增加列:  

DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
            DataGridViewTextBoxColumn Column1  = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Column1.HeaderText = "Column1";
            this.Column1.Name = "Column1";
            dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
            dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
            dataGridViewCellStyle1.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
            dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
            dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
            dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
            this.grd.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
            this.grd.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.grd.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.Column1});

三、DataGridView之间的复制

  1.1 相同标题的DataGridView的行复制:  

DataGridViewRow[] GridViewRow = new DataGridViewRow[] { };
this.DataGridView1.Rows.CopyTo(GridViewRow, 0); 
this.DataGridView2.Rows.AddRange(GridViewRow);

四、属性设置

  1.1 去掉默认空行:AllowUserToAddRows属性设置为 False;

  1.2 行高:RowTemplate.Height;

  1.3 字体大小:this.gvCardSelect.Font = new Font(this.gvCardSelect.Font.FontFamily, 15);

  1.4 AutoGenerateColumns必须在datasource属性赋值前进行赋值:  

this.gvCardSelected.AutoGenerateColumns = false;
this.gvCardSelected.DataSource = dt;

 

五、在DataGridView中单元格中增加按钮,并对按钮增加事件处理单元格的值

  1.1增加按钮处理:  

/// <summary>
        /// 记录动态添加的按钮
        /// </summary>
        private List<string> ButtonList = new List<string> { };


//在绑定数据新增行时绘制两个按钮添加到指定单元格
/// <summary>
        /// 动态添加按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvCardSelect_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            if (ButtonList.IndexOf("BtnAllowTimesInc" + e.RowIndex) < 0)
            {
                int ColumnIndex = this.gvCardSelect.Columns["ColAllowTimes"].Index;
                Button btn1 = new Button();
                btn1.Name = "BtnAllowTimesInc" + e.RowIndex; ;
                btn1.Text = "-";
                btn1.Width = 15; 
                btn1.Click += new EventHandler(BtnAllowTimesInc_Click);
                this.gvCardSelect.Controls.Add(btn1);
                btn1.Location = new System.Drawing.Point(((this.gvCardSelect.GetCellDisplayRectangle(ColumnIndex, e.RowIndex, true).X) + this.gvCardSelect.Columns["ColAllowTimes"].Width - btn1.Width), this.gvCardSelect.GetCellDisplayRectangle(ColumnIndex, e.RowIndex, true).Y);
                ButtonList.Add(btn1.Name); 

                Button btn2 = new Button();
                btn2.Name = "BtnAllowTimesAdd" + e.RowIndex; ;
                btn2.Text = "+";
                btn2.Width = 15;
                btn2.Click += new EventHandler(BtnAllowTimesAdd_Click);
                this.gvCardSelect.Controls.Add(btn2);
                btn2.Location = new System.Drawing.Point(((this.gvCardSelect.GetCellDisplayRectangle(ColumnIndex, e.RowIndex, true).X) + this.gvCardSelect.Columns["ColAllowTimes"].Width - btn1.Width - btn2.Width - 1), this.gvCardSelect.GetCellDisplayRectangle(ColumnIndex, e.RowIndex, true).Y);
                ButtonList.Add(btn2.Name);
            }
        }


/// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData(string sWhere = "")
        {
            ClearButton();
            DataTable dt = DBServiceHelper.ticketkindService.GetDataTable(UserInfo, "kind_name as cardtype,‘1‘ as AllowTimes ,‘1‘ as Selected,* ",sWhere);
            if (dt.Rows.Count > 0)
            {
                gvCardSelect.AutoGenerateColumns = false;
                gvCardSelect.DataSource = dt;
            }
        }

/// <summary>
        /// 删除上次查询添加的按钮
        /// </summary>
        private void ClearButton()
        {
            for (int i = 0; i < ButtonList.Count; i++)
            {
                Button btn = this.gvCardSelect.Controls.Find(ButtonList[i].ToString(), true)[0] as Button;
                if(btn != null)
                  this.gvCardSelect.Controls.Remove(btn);
            }
            if (ButtonList.Count > 0)
            {
                this.gvCardSelect.Refresh();
                ButtonList.Clear();
            }
        }

  1.2 行或列的宽度和长度变化后,按钮的位置要相应地进行调整:  

private void gvCardSelect_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            AlterControlLocation();
        }

        private void gvCardSelect_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            AlterControlLocation();
        }

        /// <summary>
        /// 改变控件的位置
        /// </summary>
        private void AlterControlLocation()
        {
            int ColumnIndex = this.gvCardSelect.Columns["ColAllowTimes"].Index;
            for (int i = 0; i < this.gvCardSelect.Rows.Count; i++)
            {
                Button btn1 = this.gvCardSelect.Controls.Find("BtnAllowTimesInc" + i, true)[0] as Button;
                btn1.Location = new System.Drawing.Point(((this.gvCardSelect.GetCellDisplayRectangle(ColumnIndex, i, true).X) + this.gvCardSelect.Columns["ColAllowTimes"].Width - btn1.Width - 1), this.gvCardSelect.GetCellDisplayRectangle(ColumnIndex, i, true).Y);
                Button btn2 = this.gvCardSelect.Controls.Find("BtnAllowTimesAdd" + i, true)[0] as Button;
                btn2.Location = new System.Drawing.Point(((this.gvCardSelect.GetCellDisplayRectangle(ColumnIndex, i, true).X) + this.gvCardSelect.Columns["ColAllowTimes"].Width - btn1.Width - btn2.Width - 1), this.gvCardSelect.GetCellDisplayRectangle(ColumnIndex, i, true).Y);
            }
        }

五、DataGridView列宽和标题宽度设置

  1.1、AllCells 调整列宽,以适合该列中的所有单元格的内容,包括标题单元格。 
  1.2、AllCellsExceptHeader 调整列宽,以适合该列中的所有单元格的内容,不包括标题单元格。 
  1.3、ColumnHeader 调整列宽,以适合列标题单元格的内容。 
  1.4、DisplayedCells 调整列宽,以适合当前屏幕上显示的行的列中的所有单元格的内容,包括标题单元格。 
  1.5、DisplayedCellsExceptHeader 调整列宽,以适合当前屏幕上显示的行的列中的所有单元格的内容,不包括标题单元格。 
  1.6、Fill 调整列宽,使所有列的宽度正好填充控件的显示区域,只需要水平滚动保证列宽在DataGridViewColumn.MinimumWidth 属性值以上。相对列宽由相对     DataGridViewColumn.FillWeight 属性值决定。 
  1.7、None 列宽不会自动调整,Resizeable属性为false.
  1.8、NotSet 列的大小调整行为从 DataGridView.AutoSizeColumnsMode 属性继承。

  1.9 高度和宽度自动适应内容:dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

  2.0 设置列标题不换行:dataGridView.ColumnHeadersDefaultCellStyle.WrapMode = DataGridViewTriState.False;

五、DataGridView手动添加行数据。  

               DataGridViewRow row = new DataGridViewRow();
                foreach (DataGridViewColumn c in this.GrdReadRecord.Columns)
                {
                    row.Cells.Add(c.CellTemplate.Clone() as DataGridViewCell);
                }
                row.Cells[0].Value =http://www.mamicode.com/ Cardno;
                row.Cells[1].Value =http://www.mamicode.com/ EdtCurrent_SerialNo.Text.Trim();
                row.Cells[2].Value =http://www.mamicode.com/ EdtCurrent_SerialNo.Text.Trim();

                this.GrdReadRecord.Rows.Add(row);            

 

DataGridView