Search code examples
c#datagridviewprogrammatically-created

How can I do a CellDoubleClick event on my datagridview that I created programmatically? C#


I created a panel programmatically and inside of that panel is my datagridview which created programmatically too. It's a list of supplier and I want to do a CellDoubleClick event on that datagrdiview to get its ID and the panel and data gridview will hide/close. How can I do it?

    DataGridView dgvSupp;

    private void cbSuppID_Click(object sender, EventArgs e)
    {
       pGeneral.Controls.RemoveByKey("pCatHierarchy");
       Panel pSupp = new Panel();
       pSupp.Size = new System.Drawing.Size(239, 196);
       pSupp.Location = new Point(152, 173);
       pSupp.Name = "pSupplier";
       pSupp.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
       this.Controls.Add(pSupp);
       pSupp.BringToFront();
       dgvSupp = new DataGridView();
       dgvSupp.AllowUserToAddRows = false;
       dgvSupp.AllowUserToDeleteRows = false;
       dgvSupp.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
       dgvSupp.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
       dgvSupp.Dock = System.Windows.Forms.DockStyle.Fill;
       dgvSupp.MultiSelect = false;
       dgvSupp.ReadOnly = true;
       dgvSupp.RowHeadersVisible = false;
       dgvSupp.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
       pSupp.Controls.Clear();
       pSupp.Controls.Add(dgvSupp);
       DataTable dt = pc.fetchRecord("VIEW", "FETCHCBSUPP", "", "", "", "", "", "");
       BindingSource source = new BindingSource();
       source.DataSource = dt;
       dgvSupp.DataSource = source;
    }

I tried like when you drag and drop a datagridview and click on the event properties and it's not working

    private void dgvSupp_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        DataGridViewRow row = dgvSupp.Rows[e.RowIndex];

        txtID.Text = row.Cells["Supplier ID"].Value.ToString();
    }

Solution

  • You must subscribe the event in cbSuppID_Click: dgvSupp.CellDoubleClick += dgvSupp_CellDoubleClick;.

    – @Olivier Jacot-Descombes