C# winform DataGridView 常用事件与代码操作

DataGridView 事件

1、内容被修改(选择类、下拉菜单类)

CellValueChanged // 初始化和内容提交后(失去焦点后)触发事件
CurrentCellDirtyStateChanged // 内容被修改后,触发事件(立即)

 // 失去焦点后 才会被触发
 private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
 {
     // 初始化时也会被调用
     MessageBox.Show(e.RowIndex.ToString());
 }

 // 当前单元格 内容变换
 private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
 {
     // 当前单元格 是否有未提交的更改
     if (dataGridView1.IsCurrentCellDirty)
     {
         // 提交单元格修改 至 单元格 内容被修改
         dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
     }
 }

2、点击单元格(按钮类、连接类)

CellContentClick // 单元格被点击后触发

 // 点击单元格
 private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
 {
     if (e.RowIndex == -1) return;

     DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];

     if (cell.FormattedValue.ToString() == "删除")
     { 
         System.Diagnostics.Debug.WriteLine("删除"); 
     }
     else if (cell.FormattedValue.ToString() == "修改")
     { 
         System.Diagnostics.Debug.WriteLine("修改"); 
     }
 }

代码添加列和行

 private void Form1_Load(object sender, EventArgs e)
 {
     // 代码添加列
     DataGridViewCheckBoxColumn  dgcColum1 = new DataGridViewCheckBoxColumn();
     dgcColum1.Name = "columnSelect";
     dgcColum1.HeaderText = "选择";
     dgvUser.Columns.Add(dgcColum1);

     DataGridViewTextBoxColumn dgcColum2 = new DataGridViewTextBoxColumn();
     dgcColum2.Name = "columnID";
     dgcColum2.HeaderText = "编号";
     dgvUser.Columns.Add(dgcColum2);

     DataGridViewTextBoxColumn dgcColum3 = new DataGridViewTextBoxColumn();
     dgcColum3.Name = "columnName";
     dgcColum3.HeaderText = "姓名";
     dgvUser.Columns.Add(dgcColum3);

     DataGridViewLinkColumn dgcColum4 = new DataGridViewLinkColumn();
     dgcColum4.Name = "columnDelete";
     dgcColum4.HeaderText = "删除";
     dgvUser.Columns.Add(dgcColum4);

     // 添加数据 行
     DataGridViewRow dr = new DataGridViewRow();
     DataGridViewCell cell1 = new DataGridViewCheckBoxCell();
     cell1.Value = false;
     DataGridViewCell cell2 = new DataGridViewTextBoxCell();
     cell2.Value = 1;
     DataGridViewCell cell3 = new DataGridViewTextBoxCell();
     cell3.Value = "admin";
     DataGridViewCell cell4 = new DataGridViewLinkCell();
     cell4.Value = "删除";

     dr.Cells.Add(cell1);
     dr.Cells.Add(cell2);
     dr.Cells.Add(cell3);
     dr.Cells.Add(cell4);

     dgvUser.Rows.Add(dr);
 }

C# winform DataGridView 常用事件与代码操作_第1张图片

在这里插入图片描述

你可能感兴趣的:(C#,c#)