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 > )
{
DataRow row = dt.NewRow();
for (int i = ; i < dt.Columns.Count; i++)
{
if (i == )
row[] = "合计";
if (i > )
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, );
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) < )
{
int ColumnIndex = this.gvCardSelect.Columns["ColAllowTimes"].Index;
Button btn1 = new Button();
btn1.Name = "BtnAllowTimesInc" + e.RowIndex; ;
btn1.Text = "-";
btn1.Width = ;
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 = ;
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 - ), 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 > )
{
gvCardSelect.AutoGenerateColumns = false;
gvCardSelect.DataSource = dt;
}
} /// <summary>
/// 删除上次查询添加的按钮
/// </summary>
private void ClearButton()
{
for (int i = ; i < ButtonList.Count; i++)
{
Button btn = this.gvCardSelect.Controls.Find(ButtonList[i].ToString(), true)[] as Button;
if(btn != null)
this.gvCardSelect.Controls.Remove(btn);
}
if (ButtonList.Count > )
{
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 = ; i < this.gvCardSelect.Rows.Count; i++)
{
Button btn1 = this.gvCardSelect.Controls.Find("BtnAllowTimesInc" + i, true)[] as Button;
btn1.Location = new System.Drawing.Point(((this.gvCardSelect.GetCellDisplayRectangle(ColumnIndex, i, true).X) + this.gvCardSelect.Columns["ColAllowTimes"].Width - btn1.Width - ), this.gvCardSelect.GetCellDisplayRectangle(ColumnIndex, i, true).Y);
Button btn2 = this.gvCardSelect.Controls.Find("BtnAllowTimesAdd" + i, true)[] as Button;
btn2.Location = new System.Drawing.Point(((this.gvCardSelect.GetCellDisplayRectangle(ColumnIndex, i, true).X) + this.gvCardSelect.Columns["ColAllowTimes"].Width - btn1.Width - btn2.Width - ), 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[].Value = Cardno;
row.Cells[].Value = EdtCurrent_SerialNo.Text.Trim();
row.Cells[].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 :此事件通常会在以下情况下发生:当单元格已编辑,但是更改尚未提交到数据缓存中时,或者当编辑操作被取消时。

DataGridView的更多相关文章

  1. [WinForm] DataGridView 绑定 DT && ComboBox 列绑定 Dict

    一  需求介绍 一般像枚举类型的数据,我们在数据库里存储着诸如(1.2.3.4-)或者("001"."002"."003"-)此类,但是界面 ...

  2. [Winform] DataGridView 总结(FAQ)

    Q1.  如何使单元格不可编辑? A:设置 ReadOnly 属性,可以设置的对象包括 DataGridViewRow(行).DataGridViewColumn(列).DataGridViewCel ...

  3. [Winform] DataGridView 中 DataGridViewComboBox 的可编辑

    在 DataGridView 中设置的 DataGridViewComboBox,默认是不可编辑的,即使将其列属性 DisplayStyle 设置成 ComboBox 或其他,也无法编辑: 故作如下处 ...

  4. c#datagridview

    //保证显示当前活动单元格 this.Invoke(new Action(() => { dataGridView1.CurrentCell = dataGridView1.Rows[index ...

  5. DataGridView 在下拉框添加下来事件

    DataGridView中有一种下拉框式的列,给这个列添加下拉事件时需要转化一下才可以绑定下拉事件 /// <summary> /// 服务类型 /// </summary> ...

  6. 设置DataGridView的某个单元格为ComboBox

    怎么将DataGridView的 某个单元格设为ComboBox的样式而不是整列都改变样式? 1.最简单的方法:利用DataGridView提供的DataGridViewComboBoxCell. 写 ...

  7. 用DataGridView导入TXT文件,并导出为XLS文件

    使用 DataGridView 控件,可以显示和编辑来自多种不同类型的数据源的表格数据.也可以导出.txt,.xls等格式的文件.今天我们就先介绍一下用DataGridView把导入txt文件,导出x ...

  8. 图解DataGridView编辑列

    WinForm中DataGridView功能强大,除了可以自动绑定数据源外,还可以根据需求编辑列.下面以截图说明添加编辑列的步骤(HoverTreeSCJ 项目实际界面). 1.选择DataGridV ...

  9. datagridview 单元格格式转换注意

    datagridview 单元格内容进行比较时要注意正确写法要用强制转换,否则出错Convert.ToString(grd_order.SelectedRows[0].Cells[1].Value)= ...

  10. C# DataGridView中指定的单元格不能编辑

    注意:DataGridView控件是从.NET Framework 2.0版本开始追加的. ReadOnly属性的使用 DataGridView内所有的单元格不能编辑 当DataGridView.Re ...

随机推荐

  1. IOS网络第二天 - 07-发送JSON给服务器

    *************** #import "HMViewController.h" #import "MBProgressHUD+MJ.h" @inter ...

  2. UE4实现风格化渲染(一):UserNormalTranslator工具的使用

    最近会在UE4上实现风格化渲染的需求,所以也借机写一下相关的制作教程.对应日系风格化渲染技法来说,关键还是法线的处理.   法线处理以前翻译的资料很多了,所以也不多做解释了,比如下图是最新的UE4上的 ...

  3. 基于fab自动化部署

    fab是一个python库,强大好使,可以做很多帮助你减轻工作量的事情,比如在多台服务器上部署web项目,这里就讲讲使用它简单的方法来执行部署的过程. 关于fab的安装的基本使用,网上一搜一大把,内容 ...

  4. 取到 tableview 自定义section header 上的button

    在自定义的组头上,添加了一个button,在点击cell是想取到相应的组头上的button来进行操作时(比如说隐藏.是否响应点击事件等)时,我遇到了取不到所有button的问题,试过了常规的通过vie ...

  5. Win32 设置窗口透明度 SetLayerTransparent

    注意: 在调用SetLayeredWindowAttributes 之前,需要给窗口加上WS_EX_LAYERED属性,否则会无效 void SetLayerTransparent(HWND hWnd ...

  6. SQL Server中事务、锁定和阻塞

    事务是什么 在SQL Server中事务是构成一个工作逻辑单元的一系列任务,也就说多个任务放在一起执行,这些任务要么全部执行成功,要么全部执行失败. 通过事务我们可以保证数据的完整性,例如:用户A给用 ...

  7. ActionListener的三种实现方法

    Swing是目前Java中不可缺少的窗口工具组,是用户建立图形化用户界面(GUI)程序的 强大工具.Java Swing组件自动产生各种事件来响应用户行为.如当用户点击按钮或选择菜单项目时,Swing ...

  8. blowfish ECB decode

    blowfish  ECB  Decode package main import ( "crypto/cipher" "encoding/hex" " ...

  9. 真TM操蛋——观《鬼子来了》有感

    杀日本人有罪?日本人杀中国人为何无罪?战俘?双手沾满鲜血,仇人,为何杀仇人还要被自己人判刑,被仇人斩首? 看了最后结局,我心里只有这两句话,同学说结局不好,我觉得结局恰恰很好,姜文是个很好的导演,他布 ...

  10. ionic实现点击popup区域外部分来关闭popup

    var htmlEl = angular.element(document.querySelector('html')); htmlEl.on('click', function (event) { ...