C#将父表单数据发送到子表单

时间:2014-01-11 05:16:43

标签: c# forms

尝试以另一种形式激活此功能。我希望listBox1中的对象转到label2中的标签:label3和label4。 PropertyA应该将label3和PropertyB分配给label4。它只是从form1加载数据。问题在于form2代码。当从列表框中选择一个项目时,它将编写属性以便为下一个form2实例准备它们。 其中大部分都是相当简短的代码......

制作一个简单的程序来说明......

找到解决方案....看到FORM2,这是一个在表单之间进行转换的问题,将listbox1.SelectedItems作为SpecialClass类型的对象。

 namespace WindowsFormsApplication1
{
    class SpecialClass
    {
        public string PropertyA { get; set; }
        public double PropertyB { get; set; }

        #region [Methods]
        public override string ToString()
        {
    return string.Format("PropertyA: {0}, PropertyB: {1}", this.PropertyA, this.PropertyB);
}
        #endregion
    }
}

Form1中

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void AddBtn_Click(object sender, EventArgs e)
        {
            SpecialClass o = new SpecialClass();
         o.PropertyA =  textBox1.Text;
            o.PropertyB = double.Parse(textBox2.Text);
            listBox1.Items.Add(o);
         }

        #region [Currently unused methods]
        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }
        #endregion

        private void openNewForm(object sender, EventArgs e)
        {

            Form2 form2 = new Form2(this);
            form2.Show(this);   
      }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            SpecialClass o = ((ListBox)sender).SelectedItem as SpecialClass;
            label3.Text = o.PropertyA.ToString();
            label4.Text = o.PropertyB.ToString();



        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

窗体2

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        Form1 form1Data = new Form1();
    public Form2(Form1 _form1)
    {
        InitializeComponent();
        form1Data = _form1;
    }

          private void label3_Click(object sender, EventArgs e)
        {

            SpecialClass oF2 = form1Data.listBox1.SelectedItem as SpecialClass;
            label3.Text = oF2.PropertyA.ToString();
        }

        private void Form2_Load(object sender, EventArgs e)
        {

        }
    }
}

0 个答案:

没有答案