简体   繁体   中英

How Do I pass back value from form2 textbox to listbox value in forn1 c#

Code From Form1

 private void EditBtn_Click(object sender, EventArgs e)
 {
  Form2 frm = new Form2(textBox1.Text);
  frm.ShowDialog();
  frm.Show();
 }

Code From Form 2

 public partial class Form2 : Form
    {
    private object listBox1;

    public Form2(string value)
    {
        InitializeComponent();
        textBox1.Text = value;
    }

    private void Form2_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
     {
          Form1.show();
      }
   }
}

I'm not sure if You want to keep open both forms or not. If You want to keep it open, and add items to Form1's ListBox, than there is an answer

public partial class Form1 : Form
{
    private void EditBtn_Click(object sender, EventArgs e)
    {
        // listBox1 is already set on the designer
        Form2 frm = new Form2(textBox1.Text, listBox1);
        frm.ShowDialog();
        frm.Show();
    }
}

public partial class Form2 : Form
{
    private ListBox _listBox1;

    public Form2(string value, ListBox listBox1)
    {
        InitializeComponent();
        textBox1.Text = value;
        _listBox1 = listBox1;
    }

    private void Form2_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        _listBox1.Items.Add("returned Value");
    }
}

Suggesting the below solution.

Add ListBox and Button to Form1 . Make the ListBox as public and static as in below code snippet to access this from Form2

 public static System.Windows.Forms.ListBox listBox1;

Make the button click event as below

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

Now add another form Form2. Add a text box and button to it. Make the button click event as below

 private void UpdateBtn_Click(object sender, EventArgs e)
 {
     if (UpdateBtn.Text != string.Empty)
         Form1.listBox1.Items.Add(textBox1.Text);
 }

Now,run the program. open Form2 by clicking the button "LoadForm2Btn" in Form1. Enter the text you want to add in ListBox in Form1 and click "UpdateBtn" button. You text will be added in the Listbox

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