2011-08-17 69 views
0

基本上我想要做的是我有一个字符串在主窗体上从文本框中拉出它的值。如何将字符串传递给子窗体?

然后,我生成第二个窗体的模态版本,并希望在进程的第二个窗体中使用该字符串(或主窗体textbox1.text值)。

主要形式

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Diagnostics; 
using System.IO; 




namespace Tool{ 

    public partial class MainForm : Form 
    { 
     public string hostname; 
     public MainForm() 
     { 
      InitializeComponent(); 
      textBox1.Text = hostname; 

     } 
    public void btn_test_Click(object sender, EventArgs e) 
     { 
      string hostname = textBox1.Text; 
      SiteForm frmsite = new SiteForm(); 
      frmsite.ShowDialog(); 


     } 

    } 
} 

' 子窗体

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Diagnostics; 
using System.IO; 

namespace Tool 
{ 
    public partial class SiteForm : Form 
    { 
     public string hostname {get; set; } 
     public SiteForm() 
     { 
      InitializeComponent(); 
     } 

     private void label1_Click(object sender, EventArgs e) 
     { 
      label1.Text = this.hostname; 
     } 


    } 
} 

我如何能做到这一点有什么建议?我知道必须有一个更简单的方法,对不起,我还是一个小菜鸟,我正在努力自学C#。

结果是当我点击子窗体上的标签时它是空白的,因为这个我能够推断出字符串没有正确地在两个窗体之间传递。

+0

实际上,我没有看到字符串在窗体之间传递的位置。我错过了什么吗? –

回答

2

最简单的方法是将其传递子窗体的构造函数,例如:

private string _hostname = ""; 

... 

public SiteForm(string hostname) 
{ 
    _hostname = hostname; 
    InitializeComponent(); 
} 
+1

不应该在''InitalizeComponent();' – Bosak

+0

@Bosak之后执行'_hostname = hostname;'**不需要。如果代码不与控件交互,则任何位置都可以。如果代码与控件进行交互,则需要在InitializeComponent调用之后放置代码。 – 2011-08-17 13:33:38

+0

你是来自Facepunch或其他人的Grea $ eMonkey吗?对不起,offtopic – Bosak

1

尝试挂钩到您的子窗体的Load事件并设置其hostname属性的值在事件处理上你的主要形式。

public void btn_test_Click(object sender, EventArgs e) 
    { 
     string hostname = textBox1.Text; 
     SiteForm frmsite = new SiteForm(); 
     frmsite.Load += new EventHandler(frmsite_Load); 
     frmsite.ShowDialog(); 
    } 

public void frmsite_Load(object sender, EventArgs e) 
{ 
     SiteForm frmsite = sender as SiteForm; 
     frmsite.hostname = this.hostname; 

}