开发者

How to pass a string to child form?

开发者 https://www.devze.com 2023-03-29 05:26 出处:网络
Basically what I\'m trying to do is I have a string on the main form that pulls its value from a textbox.

Basically what I'm trying to do is I have a string on the main form that pulls its value from a textbox.

I then generate a modal version of a second form and want to have that string (or the main forms textbox1.text value) usable in the second form for processes.

Main Form

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
    {
开发者_JAVA技巧        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();


        }

    }
}

' Child Form

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;
        }


    }
}

Any suggestions on how I can do this? I know there has to be a simpler way, sorry I'm still a bit of a noob and am trying to teach myself C# as I go.

The result is when I click the label on the child form it is blank, because of this I am able to deduce that the string isn't passing between the two forms correctly.


The simplest way is to pass it in the constructor of the Child form, for example:

private string _hostname = "";

...

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


Try hooking into your child form's Load event and set the value of its hostname property in an event handler on your main form.

 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;

 }
0

精彩评论

暂无评论...
验证码 换一张
取 消