zoukankan      html  css  js  c++  java
  • DataGridView

    DataGridView中的DataGridViewComboBoxColumn 让其值改变联动

    触发dataGridView1的CurrentCellDirtyStateChanged事件,并且在事件中调用DataGridView.CommitEdit 方法。

    [关于CommitEdit MSDN解释如下:将当前单元格中的更改提交到数据缓存,但不结束编辑模式。 ]

    这样我们关心的那个事件CellValueChanged就能够被顺利触发了。示例代码如下。

    private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
            {
                if (dataGridView1.IsCurrentCellDirty)
                {
                    dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
                }
            }

     

    动态绑定DataTable添加合计行的方法:

    DataTable dt = DBServiceHelper.businessDbHelper.Fill(UserInfo, sSQL);
    if (dt.Rows.Count > 0)
    {
    DataRow row = dt.NewRow();
    for (int i = 0; i < dt.Columns.Count; i++)
    {
    if (i == 0)
    row[0] = "合计";
    if (i > 3)
    row[i] = dt.Compute("Sum(" + dt.Columns[i].ColumnName + ")", null);//无效的聚合函数 Sum()和类型 String 的用法 数据库中的数据类型必须是数字
    }
    dt.Rows.Add(row);
    }
    Grd按票号明细统计.AutoGenerateColumns = true;
    Grd按票号明细统计.AlternatingRowsDefaultCellStyle = null;
    Grd按票号明细统计.DataSource = dt;

     

     

    在checkbox格式下,如果根据条件使得选中无效?

    1、在RowsAdded时间中,根据条件设置ReadOnly为true;

    2、在CellContentClick中,根据条件设置点击时不更改单元格的值;

     

    winform设置DataGridView某行某列单元格为可编辑状态

    dv.Columns["UpdSkuSonAfter"].ReadOnly = false;
    dv.Columns["UpdSkuSonAfter"].DefaultCellStyle.BackColor = Color.White;
    DataGridViewCell cell = dv.Rows[0].Cells["列名"];
    dv.CurrentCell = cell;
    dv.BeginEdit(true);   

    一、实现CheckBox列

      1.1 增加CheckBox列:

      在DataGridView中增加CheckBox列:

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

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

      

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

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

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

    主要用到了datagridview的CurrentCellDirtyStateChanged和CellValueChanged两个事件

    CurrentCellDirtyStateChanged事件是提交对checkbox状态的修改

    CellValueChanged事件是当状态提交后,也就是单元格值改变后做一些其它的操作,这里是将checkbox列的true或false状态作为tooptiptext属性设置到同一行的button列

    CurrentCellDirtyStateChanged事件代码 :


    private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
    if (this.dataGridView1.IsCurrentCellDirty) //有未提交的更//改
    {
                    this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
     }
     }

    CellValueChanged事件代码 : 


     private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
            {
                if (this.dataGridView1.Columns[e.ColumnIndex].Name.Equals("gender"))
                {
                    DataGridViewButtonCell dgvButtonCell = this.dataGridView1.Rows[e.RowIndex].Cells["btn"] as DataGridViewButtonCell;//获得button列单元格
                    DataGridViewCheckBoxCell dgvCheckBoxCell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;//获得checkbox列单元格
                    dgvButtonCell.ToolTipText = dgvCheckBoxCell.Value.ToString();//赋值
                }
            }

    二、动态添加列

      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 = Cardno;
                    row.Cells[1].Value = EdtCurrent_SerialNo.Text.Trim();
                    row.Cells[2].Value = EdtCurrent_SerialNo.Text.Trim();
    
                    this.GrdReadRecord.Rows.Add(row);            

     六、列标题样式更改:

      1、设置EnableHeadersVisualStyles为false;

      2、设置ColumnHeadersDefaultCellStyle;

    七、事件与CurrentRow:
    在RowEnter、KeyPress事件发生时,CurrentRow的值未改变。KeyUp事件发生时,CurrentRow的值已经改变。

    八、冻结列和滚动条:
    1、当存在冻结列时,水平滚动条可能没有显示出来。

    九、DataGridView列的顺序出现自动改变:

      dataGridView1.AutoGenerateColumns = false;

    datagridview CurrentCellDirtyStateChanged :此事件通常会在以下情况下发生:当单元格已编辑,但是更改尚未提交到数据缓存中时,或者当编辑操作被取消时。

  • 相关阅读:
    .NET ORM 的 “SOD蜜”--零基础入门篇
    EF+MySQL乐观锁控制电商并发下单扣减库存,在高并发下的问题
    PDF.NET SOD 开源框架红包派送活动 && 新手快速入门指引
    DataSet的灵活,实体类的方便,DTO的效率:SOD框架的数据容器,打造最适合DDD的ORM框架
    64位系统使用Access 数据库文件的彻底解决方法
    DDD为何叫好不叫座?兼论DCI与业务分析的方法论
    买的永远没有卖的精:评北京联通宽带送电视送手机优惠促销活动
    在数据库上实现类似铁路售票锁票功能
    .NET DLR 上的IronScheme 语言互操作&&IronScheme控制台输入中文的问题
    U深度利用iso文件制作U盘启动盘
  • 原文地址:https://www.cnblogs.com/qi123/p/6161064.html
Copyright © 2011-2022 走看看