0
votes

I have a windows form application with 6 datagridviews on it. I want to know if the user clicks on one of them, which datagridview was clicked. I have cell clicked events for each of the datagridviews.

I want to use it here:

dgvArray[i].Rows[j].Cells[4].Value = GlobalData[j + i * 8 + interface * 64];

dgvArray is an array of 6 DataGridViews.

2

2 Answers

5
votes

The sender is passed as first parameter to the click event handlers. Cast it to DataGridView and you have the control that was clicked.

0
votes

You should point all of the 6 events to a single event handler, which then uses the Tag property of the DataGridViews to identify which one the event came from. Here is an example:

dataGridView1.Tag = "DGV1";
dataGridView2.Tag = "DGV2";
dataGridView3.Tag = "DGV3";
dataGridView4.Tag = "DGV4";
dataGridView5.Tag = "DGV5";
dataGridView6.Tag = "DGV6";

private void dataGridView_CellClick(object sender,
    DataGridViewCellEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;

    //Use case 1:
    string dgvTag = (string)dgv.Tag;
    switch(dgvTag)
    {
        case "DGV1": /*Do Something*/ break;
        case "DGV3": /*Do Something*/ break;
        case "DGV3": /*Do Something*/ break;
        case "DGV4": /*Do Something*/ break;
        case "DGV5": /*Do Something*/ break;
        case "DGV6": /*Do Something*/ break;
    }

    //Use case 2:
    DataGridViewImageCell cell = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex];
    MessageBox.Show((string)cell.Value);
}