Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
951 views
in Technique[技术] by (71.8m points)

pass listbox item to a textbox on another form c#

I am making this simple Windows forms app in Visual studio in c#. I have two forms. On form1 I have a textbox,listbox and two buttons (one to insert into listbox from textbox and another to open form2). On form2 I only have a textbox. I just simply want, when click on a button (for opening form2) on form1, form2 to open and textbox to contain (on formLoad) selected item from listbox from form1. But when I click on button it says "Object reference not set to an instance of an object". What am I doing wrong? I am pretty sure it's something simple but I just can't get it.

Thanks in advance!

Here is my code:

on form1:

  public partial class Form1 : Form
  {
    public Form1()
    {
        InitializeComponent();
    }

    private void btnOpenForm2_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.ShowDialog();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        listBox1.Items.Add(textBox1.Text);
    }
    public string Transfer
    {
        get { return listBox1.SelectedItem.ToString(); }
    }

and on form2:

 public partial class Form2 : Form
  {
    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        Form1 f1 = new Form1();
        textBox1.Text = f1.Transfer;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because in the Form2_Load event you always create a new instance of Form1 and then access the Transfer property which accesses listBox1.SelectedItem which is not set for the newly created form.

You should rather pass a referece to form 1 in the button event:

on form1:

private void btnOpenForm2_Click(object sender, EventArgs e)
{
    Form2 f2 = new Form2(this);
    f2.ShowDialog();
}

and on form2:

public partial class Form2 : Form
{
   Form1 f1;
   public Form2(Form1 f1)
   {
       this.f1 = f1;
       InitializeComponent();
   }

   private void Form2_Load(object sender, EventArgs e)
   {
       textBox1.Text = this.f1.Transfer;
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...