如何动态访问当前的DataGridView

本文关键字:DataGridView 访问 何动态 动态 | 更新日期: 2023-09-27 18:03:45

我会尽量说清楚:)我正在动态地创建新的DataGridView,这要归功于一个按钮。

它工作得很好,但是我希望能够更改DataGridView的一个单元格的值并更新我的数据库。问题是我找不到如何获得当前聚焦的DataGridView

我试着玩这个链接中的代码,我得到了当前DataGridView的名称。但我不认为我可以操纵控制作为DataGridView。下面是我的函数:

private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    DataGridView datagridcell = new DataGridView();
    string codearticle = "'" + CodeArticle0.Text + "'";
    string division = "'" + Division0.Text + "'";
    string colonne = datagridcell.Columns[e.ColumnIndex].HeaderText;
    string valeur = sender.ToString();
    string Ligne = datagridcell.Rows[0].Cells[3].ToString();
    Controller.ControllerMenuPrincipal.updateQALigneFab(codearticle, division, 
        colonne, valeur, Ligne);
}

而不是:

DataGridView datagridcell = new DataGridView();

我想访问当前/聚焦的datagridview

我不知道这是否可能,我是一个新手在winforms。

thanks for the help

如何动态访问当前的DataGridView

解决方案正如Reza Aghaei所说,

"如果你将datagridview_cellvaluechange附加到你的动态网格的cellvaluechange,那么sender参数就是事件为它触发的DataGridView。你可以这样获取sender DataGridView: var grid = (DataGridView)sender;——Reza Aghaei"

所以我只是替换了这一行:

DataGridView datagridcell = new DataGridView();

:

var grid = (DataGridView)sender;

所以我可以使用"grid"变量来操作当前的datagridview

最终代码如下:

        private void dataGridView13_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        var grid = (DataGridView)sender; //get current datagridview
        string codearticle = "'" + CodeArticle0.Text + "'";
        string division = "'" + Division0.Text + "'";
        string colonne = grid.Columns[e.ColumnIndex].HeaderText; //get column headertext of current cell 
        string valeur = grid[e.ColumnIndex, e.RowIndex].Value.ToString(); //get new value of current cell
        string Ligne = grid[3, 0].Value.ToString(); 
        Controller.ControllerMenuPrincipal.updateQALigneFab(codearticle, division, colonne, valeur, Ligne); //calling stored procedure to update my table
    }