简体   繁体   中英

Close code generated win form with eventhandler

How to close a code generated form when a listbox item is double clicked.

Here is my code

    private void btn_batchList_Click(object sender, EventArgs e)
    {
        string[] batchList = BACH_Outward.GetOutBatchList(txtBranchId.Text, dtpHouseDt.Value.ToString("dd/MM/yyyy"), cmbCLRTYPE.SelectedValue.ToString(), "T");
        if (batchList == null)
        {
            return;
        }
        Form form = new Form();
        form.FormBorderStyle = FormBorderStyle.FixedDialog;
        form.MaximizeBox = false;
        form.MinimizeBox = false;
        form.Size = new Size(150, 325);
        form.StartPosition = FormStartPosition.Manual;
        form.Location = new Point(this.Right - 200, this.Top + 100);
        form.Opacity = 50;
        form.Text = "Batch List";
        form.Move += new System.EventHandler(this.OnMove);

        ListBox BatchList = new ListBox();
        BatchList.Size = new System.Drawing.Size(140, 315);
        form.Controls.Add(BatchList);            
        BatchList.DataSource = batchList;
        BatchList.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.listBox_MouseDoubleClick);
        form.ShowDialog();
    }

private void listBox_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        ListBox listBox = (ListBox)sender;
        if (listBox.SelectedIndex != -1)
        {
            var rect = listBox.GetItemRectangle(listBox.SelectedIndex);
            if (rect.Contains(e.Location))
            {
                // process item data here
                TxtBatchNo.Text = listBox.SelectedValue.ToString();
//want to close the popup form here.
            }

        }
    }

Now I want to close the popup form when user double clicks on an Item of the listBox.

you have to declare form object in a scope where both method can access it. then invoke the method form.Close() or change the visibility to hidden if you need to show it later.

You can close the window by obtaining a reference to the Form object and calling Close() on it:

((Form)listBox.TopLevelControl).Close();

However, I would strongly suggest creating a new form in your project so that it is its own class, and encapsulates all of its own logic. It appears that you are creating a Form object directly from within another form and mixing the logic of the two forms together. This is bad design and will make future maintenance more difficult.

This is where a closure can be nice. Simply close over the form.

 BatchList.MouseDoubleClick += (sender, args) => {
   if (someCondition) {
     form.Close();
   }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM