C# 如何将按钮中的值置于DataGridView的编辑模式中?

C# 如何将按钮中的值置于DataGridView的编辑模式中?,c#,winforms,datagridview,editmode,C#,Winforms,Datagridview,Editmode,我有个问题。我有一个datagridview和一个可编辑的列,用户可以自己写一个数字。但是我需要在按钮的帮助下写出数字。例如,我有按钮1,2,3,…9,如果用户点击这个可编辑的列(当然是在一个单元格上),然后点击按钮3,那么3就会出现在单元格中。我不知道怎么做。我知道DataGridView中有这种编辑模式,但我不知道如何使用它 编辑: 我做了这样的事。它是有效的:)。但是…当我改变sum的值时,有没有办法看到所选单元格中的变化?例如,我选择了一个单元格,sum=0,过了一段时间(当仍然选择同一

我有个问题。我有一个datagridview和一个可编辑的列,用户可以自己写一个数字。但是我需要在按钮的帮助下写出数字。例如,我有按钮1,2,3,…9,如果用户点击这个可编辑的列(当然是在一个单元格上),然后点击按钮3,那么3就会出现在单元格中。我不知道怎么做。我知道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;

         }

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

DataGridViewCell activatedCell;
然后将活动单元格设置为“CellClicked”-事件:

然后对按钮进行单击事件,在该事件中,您可以设置此激活单元格的值:

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();
}

您可以发布任何代码吗?您的datagrid是否绑定到数据源?如果您的数据绑定项实现,网格应立即反映对绑定项所做的任何更改。我无法使用VS测试此代码,但我认为这种想法应该适合您的目的。无法将“System.Windows.Forms.DataGridView”类型的对象强制转换为“System.Windows.Forms.DataGridViewCell”类型。不可能将发送方对象强制转换为单元格…所以我这样做了:int row=e.RowIndex;int col=e.ColumnIndex;activatedCell=dataGridView1.Rows[row].Cells[col];但它的工作原理与我以前的解决方案相同。当我选择单元格时,如果我按下按钮,则不会发生任何变化。当我改变单元格时,新的单元格就有了这个值。或者,现在它工作了,我根据我的需要调整了你的代码,仍然需要改变一些东西,但我认为这是一个好方法!非常感谢,我自己也不会想到的:)啊。似乎发送方总是DataGridView。正如您已经提到的,EventArgs e可以用于解析行和单元格。
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();
}