【问题标题】:C# DataGridView Checkbox checked eventC# DataGridView Checkbox 选中事件
【发布时间】:2015-12-04 14:07:09
【问题描述】:

我想在我的DataGridView 中处理CheckBox 列的Checked 事件,并根据列检查值(真/假)执行操作。我尝试使用CellDirtyStateChanged 没有任何成功。事实上,我想在用户选中或取消选中复选框后立即检测选中的更改。

这是关于我的应用程序的描述。我是 c# 的新手,正在为一个为旅行者提供住宿的地方制作一个“预订我的房间”应用程序。这个屏幕可以很好地解释我希望达到的目标;

这是一个.GIF of a software,它计算员工的小时工资,这张照片是我实际想要构建的示例:

DataGridView 中显示我的表格的代码是:

OleDbConnection connection = new OleDbConnection();
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select id,cusid,cusname,timein,
timeout,duration,amount,remark from entry";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;

我使用这个添加了复选框列;

DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();
checkColumn.Name = "logout";
checkColumn.HeaderText = "Logout";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;
checkColumn.FillWeight = 10;
dataGridView1.Columns.Add(checkColumn);

每当用户从登录屏幕登录时,都会在表中插入一个新行,因此 dgv 将被更新,并带有相应的用户条目。 我不明白如何将这些复选框与 datagridview 链接我尝试了 celldirtystatechanged 但没有任何效果,将行与复选框相关联的正确方法是什么。

【问题讨论】:

  • 您可以处理DataGridViewCellContentClick 事件并将更改这些单元格的逻辑放在那里。

标签: c# winforms checkbox datagridview


【解决方案1】:

您可以处理DataGridViewCellContentClick 事件,并将更改这些单元格的逻辑放在那里。

关键是使用CommitEdit(DataGridViewDataErrorContexts.Commit) 将当前单元格中的更改提交到数据缓存而不结束编辑模式。这样,当您在此事件中检查单元格的值时,它会返回您在单击后当前在单元格中看到的当前选中或未选中的值:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    //We make DataGridCheckBoxColumn commit changes with single click
    //use index of logout column
    if(e.ColumnIndex == 4 && e.RowIndex>=0)
        this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);

    //Check the value of cell
    if((bool)this.dataGridView1.CurrentCell.Value == true)
    {
        //Use index of TimeOut column
        this.dataGridView1.Rows[e.RowIndex].Cells[3].Value = DateTime.Now;

        //Set other columns values
    }
    else
    {
        //Use index of TimeOut column
        this.dataGridView1.Rows[e.RowIndex].Cells[3].Value = DBNull.Value;

        //Set other columns values
    }
}

【讨论】:

  • 这项工作只需添加 this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick);到我的设计师来源
  • 是的,您可以像以前那样使用代码或使用设计器来完成。要使用设计器添加它,您可以在设计器上选择网格,然后按 F4 查看属性,在属性窗口中,从工具条中选择事件,然后在事件列表中双击 CellContentClick
猜你喜欢
  • 2012-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 1970-01-01
相关资源
最近更新 更多