如何将来自按钮的值置于DataGridView的编辑模式

本文关键字:DataGridView 模式 编辑 按钮 何将来 将来 | 更新日期: 2023-09-27 18:05:21

我遇到了一个问题。我有一个datagridview和一个列是可编辑的,用户可以自己写一个数字。但是…我需要在按钮的帮助下写数字。例如我有按钮1 2 3。9,如果用户单击这个可编辑的列(当然在一个单元格上),然后单击按钮3,然后3出现在单元格中。我不知道该怎么做。我知道有这个EditMode在DataGridView,但我不知道如何使用它。

编辑:我做了这样的事情。而且确实有效:)。但是…是否有一种方法可以看到所选单元格的变化,当我改变sum的值?例如,我选择一个单元格,sum=0,过了一段时间(当相同的单元格仍然被选中时)sum变为13,但是我不会看到所选单元格中的这些变化,当我选择不同的单元格时,它将具有13。是否有任何方法可以查看所选单元格中的值,当它发生变化?

dataGridView1.CellClick += CellClicked;
private void CellClicked(object sender,DataGridViewCellEventArgs e)
        {
            int row = e.RowIndex;
            int col = e.ColumnIndex;
            dataGridView1.Rows[row].Cells[col].Value = sum;
         }

如何将来自按钮的值置于DataGridView的编辑模式

在类的根目录中创建一个新变量,用于保存上次单击的单元格:

DataGridViewCell activatedCell;

然后将活动单元格设置为"CellClicked"-event:

private void CellClicked(object sender,DataGridViewCellEventArgs e)
{
   activatedCell = ((DataGridView)sender).Rows[e.RowIndex].Cells[e.ColumnIndex];
}

然后为您的按钮创建一个点击事件,其中您将值设置为此激活单元格:

void Button_Click(Object sender, EventArgs e)
{
    // If the cell wasn't set, return
    if (activatedCell == null) { return; }
    // Set the number to your buttons' "Tag"-property, and read it to Cell
    if (activatedCell.Value != null) { activatedCell.Value = Convert.ToDouble(((Button)sender).Tag) + Convert.ToDouble(activatedCell.Value);
    else { activatedCell.Value = Convert.ToDouble(((Button)sender).Tag); }
    dataGridView1.Refresh();
    dataGridView1.Invalidate();
    dataGridView1.ClearSelection();
}