Search code examples
c#winformsdatagridvieweditmode

How to put values from buttons in the edit mode of a DataGridView?


I've got a problem. I have a datagridview and one column which is editable, user can write a number by himself. But.... i need to write the number with the help of the buttons. So for example I have buttons 1,2,3,...9 and if user clicks on this editable column(on one cell of course) and then clicks button 3 then 3 appears in the cell. I have no idea how to do it. I know there is this EditMode in DataGridView but I don't know how to use it.

EDIT: I did sth like this. And it works:). But...is there a way to see the changes in selected cell when I change the value of sum? For example, I select a cell and sum=0, after a while(when the same cell is still selected) sum changes to 13, but I won't see these changes in the selected cell, when I will select different cell it will have 13. Is there any way to see the value in selected cell when it changes?

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;

         }

Solution

  • Make a new variable in your class' root, where you save the last clicked cell:

    DataGridViewCell activatedCell;
    

    Then set the active cell at your "CellClicked"-event:

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

    Then make a click event to your buttons, where you set value to this activated cell:

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