简体   繁体   中英

C# Passing a value a new form

I got windows form am trying to pass value from that form to new one, when an button is clicked. using:

private void Edit_button_Click(object sender, EventArgs e)
        {
             for (int i = 0; i < listBox1.SelectedItems.Count; i++)
            {

             Edit item = new Edit(int.Parse(listBox1.SelectedIndex.ToString()));
            item.ShowDialog();

            }
        }

When I run the program it doesn't show the form I designed it shows this instead 问题

But when i change the code to this:

 Edit item = new Edit();
   item.ShowDialog();

run it, it display the right thing, but doesn't pass a value to the second form. 在此输入图像描述

I there a way to pass a value to another form?

Add a property

Edit item = new Edit();
item.Value = 5;
item.ShowDialog();

EDIT:

You have to define this property to use it. Extend your Edit class like that:

class Edit {
    ...
    public int Value { get; set; }
    ...
}

Make Sure that your parameterised constructor has InitiaizeComponent() in its body. As this function name specifies it initializes components of your form which are company label, textbox and button.

I'll tell you how.

Create a parameterized constructor of edit form. Pass that value into a variable

public class Edit
{
    public int val = 0;

    public Edit()
    { 
        InitializeComponent();
    }

    public Edit(int a)
    {
        val = a; 
        InitializeComponent();
    }

    public void Edit_Load()
    {
      txtbox.Text = val.ToString();
    }
}

and call edit from first form like

Edit item = new Edit(5);

只是一个猜测:在你自己的构造函数中,你忘了调用IntializeComponents()。

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