0

I have a windows form where data is being fetched from multiple SQL tables. If the required data is present , then it is displayed in dynamically generated DataGridView. I have added a button and a cellclick event to these dynamically generated datagridviews. The issue is that the cellclick event of different datagridviews references to the same datagridview(ex. - here in the below image - if I click "2" then data from "1" is picked up).

enter image description here

The code is as per below

d3 = new DataGridView();
d3.DataSource = ds;
d3.CellClick += datagridview_CellClick;
d3 =addbuttontodatagridview(d3);
addtopanel(d3);

The cell click event is -

private void datagridview_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if(e.ColumnIndex==0)
        {
            Console.WriteLine(d3.Rows[e.RowIndex].Cells[2].Value.ToString()); 
            Console.WriteLine(e.RowIndex);
        }

I understand that since I am assigning all datagridviews to d3, hence it is referencing only to the first one. But I am not sure how can I make dynamic cell click events for multiple dynamically created datagridviews

Mukund Banka
  • 66
  • 1
  • 7
  • 1
    Since all the grids are subscribing to the same cell click event, then you will need to look at the `sender` to see “which” grid was clicked by checking the grids name. Something like… `DataGridView clickedGrid = (DataGridView)sender;` … then check `clickedGrid`’s name. – JohnG May 22 '22 at 14:33
  • Thanks. This worked!. I needed to just use sender object of click event – Mukund Banka May 22 '22 at 14:42
  • If you will perform the SAME actions on any grid when a cell is clicked… then it will not matter “which” grid was clicked. All you need to do is cast the `sender` to a `DataGridView` and apply the cell click actions on THAT grid. – JohnG May 22 '22 at 15:11

0 Answers0