0

这个问题是以下问题的后续问题: C# Text don't display on another form after double click an item in listbox

现在我在 form3 的文本框中输入了我的值。在form3中按“确定”后,如何将值传回form1以在listbox10中显示?以下是我的 form3 编码,但它不起作用:

private void button1_Click(object sender, EventArgs e)
{   
    //This is the coding for "OK" button.
    int selectedIndex = listBox10.SelectedIndex;
    listBox10.Items.Insert(selectedIndex, textBox1.Text);
}
4

3 回答 3

1

您可以将公共财产放在 form3 上:

public partial class form3 : Form
{
    public String SomeName
    {
        get
        {
            return textbox1.Text;
        }
    }

    ...
    private void buttonOK_Click(object sender, EventArgs e)
    {
        DialogResult = DialogResult.OK;
        Close();
    }

    private void buttonCancel_Click(object sender, EventArgs e)
    {
        DialogResult = DialogResult.Cancel;
        Close();
    }
 }

在你打开form3的form1中,在ShowDialog之后,你会写:

if (form3.ShowDialog() == DialogResult.OK)
{

    int selectedIndex = listBox10.SelectedIndex;

    if (selectedIndex == -1) //listbox does not have items
        listbox10.Add(form3.SomeValue);
    else
        listBox10.Items.Insert(selectedIndex, form3.SomeName);
}
于 2012-10-09T10:02:08.310 回答
0

做这样的事情:

//form1:
public void add(int num)
{
  //add num to the list box.
}

现在,form3 应该在构造函数中获取 form1 的一个实例,并保存它:

//in form3:
private form form1_i
public form3(form i_form1)
{
  .
  .
  .
 form1_i = i_form1;
}

并在form3中单击按钮,调用addform1中的函数。

于 2012-10-09T10:00:49.433 回答
0

它应该是这样的,这是最安全的方法,事实上,如果您在 Windows Mobile 上工作,这是不会使应用程序崩溃的唯一方法。在桌面版本中,它可能会在调试版本中崩溃。

 public partial class Form1 : Form
{
    public string name = "something";
    public Form1()
    {
        InitializeComponent();
    }

    public delegate void nameChanger(string nme);
    public void ChangeName(string nme)
    {
        this.name = nme;
    }
    public void SafeNameChange(string nme)
    {
        this.Invoke(new nameChanger(ChangeName), new object[] { nme });
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Form3 f3 = new Form3(this);
        f3.Show();
    }

}

public partial class Form2 : Form
    {
        Form1 ff;
        public Form2(Form1 firstForm)
        {
            InitializeComponent();
            ff = firstForm;
        }

    private void button2_Click(object sender, EventArgs e)
    {
        ff.SafeNameChange("something different from the Form1");
        this.Close();
    }
}
于 2012-10-09T10:09:16.383 回答