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. DOS 命令For精解示例

    最基本形态: 在cmd 窗口中:for %I in (command1) do command2 在批处理文件中:for %%I in (command1) do command2 在批处理中,FOR ...

  2. java-int类型:int默认为0导致更新操作未赋值的情况下将值更新为0

    日常开发中,做更新操作的时候的处理方法为:当这个字段有值则更新,没有值就不更新,在mybatis的xml中表现为: <!-- 修改记录,只修改只不为空的字段 --> <update ...

  3. run time

    http://www.cnblogs.com/yswdarren/p/3619303.html

  4. shudupoj2676

    #include<stdio.h> int num,v[100][2],map[10][10]; bool judge(int x,int y,int k) {  int i,j,it,j ...

  5. 谈谈对Spring IOC的理解【转】

    学习过Spring框架的人 一定都会听过Spring的IoC(控制反转) .DI(依赖注入)这两个概念,对于初学Spring的人来说,总觉得IoC .DI这两个概念是模糊不清的,是很难理解的,今天和大 ...

  6. Vue 2.0 + Vue Router + Vuex

    用 Vue.js 2.x 与相配套的 Vue Router.Vuex 搭建了一个最基本的后台管理系统的骨架. 当然先要安装 node.js(包括了 npm).vue-cli 项目结构如图所示: ass ...

  7. lnmp配置Yii2规则

    nginx配置: 参考地址:http://www.cnblogs.com/grimm/p/5389970.html location / { try_files $uri $uri/ /index.p ...

  8. Android NDK常见配置问题的解决方案

    添加NDK包时出现"Not a valid NDK directory" 在解压的android-ndk-rxxx文件夹中新建一个txt文件,将名字包括后缀更改为ndk-build ...

  9. Immutable api example

    var temp=[{name:"kitty",age:31},{name:"ff",age:22},{name:"kitty",age:4 ...

  10. 【爬虫】BeautifulSoup之爬取百度贴吧的帖子

    在网上看到爬百度贴吧的例子,仿照写了一个用BeautifulSoup实现的,直接上代码吧 #coding:gbk import urllib2 from bs4 import BeautifulSou ...