开发者

Problem getting value from DatagridView cell

I have a DataGridView that is bound to a DataTable. The data in the DataTabl开发者_C百科e is shown in a chart(I am using Microsoft Charting). After a user edits a cell in the DataGridView the value is validated then saved in the DataTable. This is done automatically(the databinding mechanism takes care of this) and works just fine.

My problem is the following: I need to send the value to the DataTable when the user presses a key, without taking the cell out of edit mode. I need this so I can update the chart in a "real-time" way.

I've tried something like this:

    void infoDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        e.Control.KeyUp += new KeyEventHandler(Control_KeyUp);          
    }

    void Control_KeyUp(object sender, KeyEventArgs e)
    {
        this.Validate();
        UpdateChart();
    }

This is part of the code belonging to the form. But this takes out the current cell from edit mode. Maybe I could manually set the value in the datatable but in Control_KeyUp I have no idea which cell is being edited.

If you have better ideas please don't hesitate to share them. :)


Use CurrentCellDirtyStateChanged event

private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
   if(dataGridView1.IsCurrentCellDirty)
   {
      dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
   }
}

This sends the cells value to the DataTable without bringing the cell out of edit.


Instead of validating the whole datagridview again, could you just commit the changes and begin them again, so something like this:

void Control_KeyUp(object sender, KeyEventArgs e)
{
   dataGridView1.EndEdit();
   UpdateChart();
   dataGridView1.BeginEdit(false);
}


Remus,

What about something like this:

private void infoDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
   dataTable.Rows[e.RowIndex].ItemArray[e.ColumnIndex] = infoDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
   UpdateChart();
}

The advantage here is to update your data table and your chart without touching the datagridview (so you don't have to worry about the edit mode etc).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜