简体   繁体   English

将对象从一种窗口形式传递到另一种形式

[英]Passing object from one windows form to another

I have two windows forms in my application. 我的应用程序中有两个Windows窗体。 First one is Main form and the second one is lookup form. 第一个是Main表单,第二个是Lookup表单。 I'm trying to open lookup form from the main form in a text box key leave event and then I'm opening the lookup form. 我试图在文本框键离开事件中从主窗体打开查找表单,然后打开查找表单。 My lookup form has a data grid view and I' loading it in the form load event of the lookup form. 我的查找表单具有数据网格视图,并且正在将其加载到查找表单的表单加载事件中。 I'm reading my selected value on the grid view of the lookup window to an object. 我正在将查询窗口的网格视图上的所选值读取到对象。 I want to close the lookup window as soon as I read the values of the selected row to the object and I want to pass it to the main form? 我想在将所选行的值读取到对象并将其传递给主窗体后立即关闭查找窗口? How can I do that? 我怎样才能做到这一点? This is what I have done. 这就是我所做的。 In the main form. 以主要形式。

        LookupModelType="";
        if (e.KeyCode.Equals(Keys.F3))
        {
            foreach (Form frm in Application.OpenForms)
            {
                if (frm is FormControllers.Lookup)
                {
                    if (frm.WindowState == FormWindowState.Minimized)
                    {
                        frm.WindowState = FormWindowState.Normal;
                        frm.Focus();
                        return;
                    }
                }
            }
                LookupModelType = "Product";
                FormControllers.Lookup newLookUp = new FormControllers.Lookup(LookupModelType);                
                newLookUp.ShowDialog(this);
        }

In the lookup window 在查找窗口中

  private string GridType = "";
        public Lookup(String  LookupModelType)
        {
            InitializeComponent();
            this.GridType = LookupModelType; 
        }

        private void Lookup_Load(object sender, EventArgs e)
        {
            if (GridType == "Product")
            {
                using(DataControllers.RIT_Allocation_Entities RAEntity  = new DataControllers.RIT_Allocation_Entities())
                {
                    dgvLookup.DataSource = RAEntity.TBLM_PRODUCT.ToList<DataControllers.TBLM_PRODUCT>();
                }  
            }
            dgvLookup.ReadOnly = true;
        }

        private void dgvLookup_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }
            int index = e.RowIndex;
            dgvLookup.Rows[index].Selected = true;
        }

you can do it like blow : 你可以像打击一样做到:

in the Main form : 以主要形式:

   private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.F3)
        {
            LookupForm look = new LookupForm();
            var result  = look.ShowDialog();

            if(result == DialogResult.OK)
            {
                MessageBox.Show(look.data.ToString());
            }
        }
    }

and in the look up form you have to declare 1 variable and fill whenever cell clicked 在查找表单中,您必须声明1个变量并在每次单击单元格时进行填充

public partial class LookupForm : Form
{
    public object data = new object();
    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        data = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
        this.DialogResult = DialogResult.OK;
        this.Close();
    }
}

of course, for better performance, you can declare the variable in specific type 当然,为了获得更好的性能,您可以声明特定类型的变量

To share data between Parent Child forms using events, here are the things needed: 要使用事件在“父子”表单之间共享数据,需要执行以下操作:

  1. A public custom event args class to share data. 一个公共自定义事件args类,以共享数据。
  2. Child form to have a event. 子窗体有一个事件。
  3. In your parent form whenever you create an instance of child, you need to register eventhandlers 无论何时创建子实例,都需要在父表单中注册事件处理程序。

Please note that the code below is just a demo code and you will need to add null checks etc. to make it "robust". 请注意,下面的代码只是一个演示代码,您将需要添加null检查等以使其“健壮”。

Custom event args below 下面的自定义事件参数

public class ValueSelectedEventArgs : EventArgs
{
    public object Value { get; set; }
}

Your lookup form should have the following event declared: 您的查询表单应声明以下事件:

        public event EventHandler ValueSelected;

        protected virtual void OnValueSelected(ValueSelectedEventArgs e)
        {
            EventHandler handler = ValueSelected;
            if (handler != null)
            {
                handler(this, e);
            }

            // if you are using recent version of c# you can simplyfy the code to ValueSelected?.Invoke(this, e);     
        }

In my case I am firing the event on listbox selected index change and closing the form as well. 以我为例,我在选定索引更改的列表框上触发事件,并同时关闭表单。 Code for it: 代码:

        private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var i = this.checkedListBox1.SelectedIndex;
            ValueSelectedEventArgs args = new ValueSelectedEventArgs();
            args.Value = i;
            OnValueSelected(args);
            this.Close();
        }

Finally in the parent form you have to register for the eventhandler 最后,您必须在父表单中注册事件处理程序

private void textBox1_Leave(object sender, EventArgs e)
{
    lookup myLookup = new lookup();
    myLookup.ValueSelected += MyLookup_ValueSelected;
    myLookup.Show();
}

    private void MyLookup_ValueSelected(object sender, EventArgs e)
    {
        textBox2.Text = (e as ValueSelectedEventArgs).Value.ToString();

    }

I personal like to add dynamically the lookup window, and I do something like this: 我个人喜欢动态添加查找窗口,并且执行以下操作:

        //examble object
        class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
        // the value which you want to get from datagridview
        private Person _selectedValue;
        // the datagridview datasource, which you neet to set 
        private IEnumerable<Person> _gridDataSource = 
            new List<Person>()
                {
                    new Person {FirstName="Bob",LastName="Smith" },
                    new Person {FirstName="Joe",LastName="Doe"}
                };

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode== Keys.F3)
            {
                var btnOk = new Button() { Text = "Ok", Anchor= AnchorStyles.None };
                var btnCancel = new Button() { Text = "Cancel",Anchor= AnchorStyles.Right };

                var dg = new DataGridView();
                var bs = new BindingSource();
                bs.DataSource = _gridDataSource;
                dg.DataSource = bs;
                dg.Dock = DockStyle.Fill;
                dg.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

                //setup a layout wich will nicely fit to the window
                var layout = new TableLayoutPanel();
                layout.Controls.Add(dg, 0, 0);
                layout.SetColumnSpan(dg, 2);
                layout.Controls.Add(btnCancel, 0, 1);
                layout.Controls.Add(btnOk, 1, 1);
                layout.RowStyles.Add(new RowStyle(SizeType.Percent));
                layout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                layout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent));
                layout.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
                layout.Dock = DockStyle.Fill;

                //create a new window and add the cotnrols
                var window = new Form();
                window.StartPosition = FormStartPosition.CenterScreen;
                window.Controls.Add(layout);


                // set the ok and cancel buttons of the window
                window.AcceptButton = btnOk;
                window.CancelButton = btnCancel;
                btnOk.Click += (s, ev) => { window.DialogResult = DialogResult.OK; };
                btnCancel.Click += (s, ev) => { window.DialogResult = DialogResult.Cancel; };

                //here we show the window as a dialog
                if (window.ShowDialog() == DialogResult.OK)
                {
                        _selectedValue =(Person) bs.Current;
                        MessageBox.Show(_selectedValue.FirstName);
                }
            }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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