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. Yii源码阅读笔记(三十一)

    Widget类中开始,获取视图对象,获取widget ID,渲染视图,获取路径方法注释: private $_id; /** * Returns the ID of the widget. * 返回插 ...

  2. DP HDU1421

    搬寝室 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submiss ...

  3. VSCODE 插件初探

    写在前面 分享一个vscode插件background(用于改变背景).点击直接跳到vscode插件开发步骤 做vscode的插件,很久就有这个想法了,但是一直因为这样,那样的事情耽误,放弃了N次.不 ...

  4. 一步一步来做WebQQ机器人-(五)(发送消息||完结)

    × 本篇主要是: 发送QQ消息(to:好友,群),以及对小黄鸡抓包利用它的语言库 本文是WebQQ流程的最后一章 最后一章内容不多但我还是啰嗦,可能对大部分人都已知晓的流程方法我也会介绍一下 前面几个 ...

  5. HTML:document.activeElement

    今天遇到一个很郁闷的问题: document.activeElement获取当前获得焦点的元素,在chrome总是得到body,后来经过试验得到结果如下: document.activeElement ...

  6. pdb调试技巧

    1.先import pdb 在适当的位置加上pdb.set_trace(),在cmd中运行脚本,就可以看到调试的提示符 2.常用的调试命令 h(elp),会打印当前版本,pdb可用的命令,如果要查询某 ...

  7. c++多态的实现

    在面试中常常会有面试官问道,c++的多态的实现机制.那么,多态到底该如何实现呢? 多态的简单介绍 一般来说,多态分为两种,静态多态和动态多态.静态多态也称编译时多态,主要包括模板和重载.而动态多态则是 ...

  8. Python开发【第十章】:I/O多路复用、异步I/O(综合篇)

    近期心得:国庆节放假再加上近期工作太忙,已经有半个月没更新博客了,程序更别说了,也没怎么去写,自己给自己着实放了个大假.谈谈感受的话,没有python的日子,每天看书.看电影.各种玩,还有爸妈伺候着, ...

  9. JavaScript增强AJAX基础

    <title>js类型</title> <meta http-equiv="content-type" content="text/html ...

  10. Spring Boot项目中使用jdbctemplate 操作MYSQL数据库

    不废话,先来代码 pom文件: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http ...