简体   繁体   English

如何将值从form2文本框传递回forn1 c中的列表框值#

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

Code From Form1 Form1的代码

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

Code From Form 2 表格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 如果你想保持它打开,并将项目添加到Form1的ListBox,那么就有答案

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 . ListBoxButton添加到Form1 Make the ListBox as public and static as in below code snippet to access this from Form2 将ListBox设置为公共和静态,如下面的代码片段,从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. 现在添加另一个表单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. 单击Form1中的“LoadForm2Btn”按钮打开Form2。 Enter the text you want to add in ListBox in Form1 and click "UpdateBtn" button. 在Form1中输入要在ListBox中添加的文本,然后单击“UpdateBtn”按钮。 You text will be added in the Listbox 您的文本将添加到列表框中

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

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